foreachexplodeimplodemysql-insert-id

Insert multiple check box values into multiple rows in one table?


I have multiple check box with the same input name like this

<input type="checkbox" name="pop[]" value="pop1">pop1<br>
<input type="checkbox" name="pop[]" value="pop2">pop2<br>
<input type="checkbox" name="pop[]" value="pop3">pop3<br>
<input type="checkbox" name="pop[]" value="pop4">pop4 <br>
<input type="checkbox" name="pop[]" value="pop5">pop5<br>
<input type="checkbox" name="pop[]" value="pop6">pop6 <br>
<input type="checkbox" name="pop[]" value="pop7">pop7<br>
<input type="checkbox" name="pop[]" value="pop8">pop8 <br>

The database table contains two columns (ID and POPNAME).

I need every pop checked to inserted into database in separate row but with the same ID so this is my PHP:

$pop = implode(',', $_POST['pop']);
mysql_query("INSERT INTO pops (id, popname) VALUES (LAST_INSERT_ID(), '$pop')");

But this not working. I tried to stick to this answer make explode then use for each but also not working. This is the foreach code:

$pop = implode(',', $_POST['pop']);
$pops = explode(',', $pop);
foreach ($pops as $pop )
{
    mysql_query("INSERT INTO pops (id, popname) VALUES (LAST_INSERT_ID(), '$pop')");
}

Am I missing something!


Solution

  • It's solved.

    Problem is $pop defined twice one as a var another one in foreach

    So after rename the first var every thing ok

    $popimp = implode(',', $_POST['pop']);
    $pops = explode(',', $pop);
    foreach ($pops as $pop )
    {
    mysql_query("INSERT INTO pops (id, popname) VALUES (LAST_INSERT_ID(), '$pop')");
    }