I’m trying to copy Kevin Yank’s method for inserting the values from multiple checkboxes (called “skill”) into a lookup db table. However, only 1 item ends up in the db per entry. Using code from Ch7 PHP & MySQL Novice to ninja. Is something wrong? I’ve followed the script as closely as I can and the example is practically identical! Entire form submits but no error thrown.
This is the relevant PDO script:
$insertID = $pdo->lastInsertId();
if (isset($_POST['skill']))
{
try
{
$skillsql= 'INSERT INTO freelance_skills SET flid = :flid, skillid = :skillid';
$s = $pdo->prepare($skillsql);
foreach ($_POST['skill'] as $skillid);
{
$s->bindValue(':flid', $insertID);
$s->bindValue(':skillid', $skillid);
$s->execute();
}
}
catch (PDOException $e)
{
$error ='Error adding user skills';
include 'error.html.php';
exit();
}
Should you increment $insertID in the loop somewhere as you add skills?
No- that refers to the skill owner (previous query not shown), I am adding multiple skills (via checkbox) per single user (rest of form gathers profile info), so it remains constant. The $insertID refers to that user’s (just added) profile ID.
It makes no difference- the two lines are equivalent, though I did try anyway! I got the code straight out of the book, so I’m surprised it doesn’t work!
Thanks for the tip, at least I now know that the whole array is properly sent. I’ve cut out a few irrelevant bits for clarity & confidentiality. That would appear to leave the PDO handler or the database table itself, both of which are copied from the book! The table records 21, 34, so it would appear that the last array item is the only one making it through.
Okay, I’m confident that semi-colon is your issue. Here is why:
The semi-colon is telling PHP, this is the end of the foreach statement. So it is looping over your skills, placing each one in $skillid but never executing the execute command for your prepared statement because the semi-colon tells it there is nothing more for the foreach to process.
Removing the semi-colon now makes the content inside the curly braces part of the foreach statement and therefore it should execute that logic for each skill.