I'm trying to code a simple grocery list web app for my family to use where the user would check the items they want to add to their list and then have it added to a table for future retrieval. But I am running into trouble while trying to insert an array along with the username into a MySQL database. I've searched around for an answer, but cannot find one that satisfies the following:
- Inserts both an array and a non-array.
- Does not use deprecated mysql_ functions.
Ideally, I would love to use PDO since I have some other queries using PDO. I know the array is being passed because I print it out successfully on the page on which I wish to execute the query. Below is what I have so far.
HTML Form (the checkbox values are populated from another MySQL table):
<div class="ui-body">
<? while($row = $resultRedMeat->fetch(PDO::FETCH_ASSOC)){
echo '<label><input type="checkbox" id="groceryListItem[]" name="groceryListItem[]" value="'.$row['food'].'">'.$row['food'].'</label>';
}?>
</div>
PHP Code to Insert
$groceryListItems = $_POST['groceryListItem'];
$q = $db->prepare("INSERT INTO `grocerylist`
SET `username` = $username, `food` = ?");
foreach((array)$groceryListItems as $groceryListItem){
$q ->execute($username, array($groceryListItem['groceryListItem']));
}
The errors I get in my error log are:
- PHP Warning: Illegal string offset 'groceryListItem'
- PHP Warning: PDOStatement::execute() expects at most 1 parameter, 2 given
While all the values being passed are from a database and there is no user entry, if you guys think it is still good to protect against injection, I wouldn't mind some advice on that, too, in this context.
Thanks so much for your help!