That's because you need to create and execute the statement within the foreach() loop. As it is, your query is built an executed after the foreach loop has run, meaning you're only borrowing the last value obtained from the loop.
Alternatively, a better way might be to build a string inside the foreach loop (constantly adding on to the end of it) like so:
$values = '';
foreach($qty as $key => $value) {
$values .= "(CURDATE(),'".$key."',".$_SESSION['userid'].",'".$value."'), ";
}
$stmt = 'INSERT INTO cookie_order (dateColumn, cookieID, userid, quantity) VALUES ' . rtrim($values, ', ');
Here's a few things I need to mention about your SQL queries:
You're not sanitizing the data! You should NEVER place user-supplied data directly into a SQL query - you're leaving yourself vulnerable to SQL injection attacks. Instead, you should the output of a function such as [man]mysql_real_escape_string/man.
-
It's not considered good SQL query practice to use a VALUES() clause in an INSERT query without naming the columns.
Because of you not using a column list, you use a blank string for the auto_increment field. Instead, you should simply omit this field entirely from your SQL queries and let the DB handle it.
Instead of having PHP generate a date (and creating another variable), I just let MySQL take care of the date with the CURDATE() function.
How are these "orders" identified? You have new rows for each product... how do you select all of the rows for an order I place? I'm guessing you have a WHERE clause that identified both my user id as well as the date that I placed the order. Now, what happens if I place two separate orders on the same day? How do you know which items belong to which order? I think a slight redesign of your SQL structure might be in need here.