将多个复选框值插入到多个行中 table?

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

我有多个具有相同输入名称的复选框,如下所示

<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>

数据库 table 包含两列(IDPOPNAME)。

我需要检查每个 pop 以单独的行插入数据库但具有相同的 ID 所以这是我的 PHP:

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

但这不起作用。我试着坚持这个 answer make explode 然后用于每个但也不起作用。这是 foreach 代码:

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

我是不是漏掉了什么!

解决了

问题是 $popforeach

中定义了两次,一个作为 var 另一个

所以在重命名第一个变量后一切正常

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

PDO php: 数据库连接代码:

<?php
$dbhost = 'localhost';
$dbname = 'yourDB';
$dbuser = 'root';
$dbpass = '';

try {
    $db = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpass);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}

catch(PDOException $e) {
    echo "Connection error: ".$e->getMessage();
}
?>

和php代码:

 $pop= implode(', ', $_POST['pop']);
 $statement = $db->prepare("INSERT INTO popTable (pop) VALUES (?)");
 $statement->execute(array($pop));
 $success_message = "Order's has been inserted successfully.";

html:

<form action="pop_form">
        <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>
   <input type="submit" value="Submit"/>
</form>