Basically, a user is filling in a form to enter a product, and then stating this product is ‘specifically’ for a user by ticking checkboxes for those users.
Product Name: foo
Specific Users:
- Bob
- Bill
- Ben
- Rob
So the user can ‘check’ 1 or more of the users to link the product with.
I have set-up database tables:
USER
| userID | name |
PRODUCTS
| productID | name |
LINKTABLE
| linkID | productID | userID |
What I’d like to happen is when the user checks ‘Bill’ and ‘Ben’ and clicks ‘Submit’, the product is added to the product table, the new productID is returned, a loop happens on an INSERT script to add a new record into the LINKTABLE with the productID and userID for each of the checked users.
So far I’ve got to the bit of inserting the product details and returning the productID, but I’m struggling with the loop to insert the productID and userID into the link table.
$product = $_POST["product"];
$sql = "INSERT INTO products ('name') VALUES ($product);
$result = mysql_query($sql);
$newProductID = mysql_insert_id();
I tried this:
if(!empty($_POST['users'])) {
foreach($_POST['users'] as $userID)
{
$sql = "INSERT INTO linktable (productID, userID) VALUES (".$newProductID.", ".$userID.")";
$result = mysql_query($sql) or die(mysql_error()."<br />".$sql);
}
But that threw an error of:
Warning: Invalid argument supplied for foreach() in ….
On the line of the ‘foreaach’ loop.
Any help would be great. Thanks!
I suspect that
$_POST['users']isn’t an array. What does your checkboxes look like in your html? They need to look like this:Notice the name
users[]Now you can do: