在一个表中将多个复选框值插入多行?

时间:2015-04-24 23:27:11

标签: foreach explode implode mysql-insert-id

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

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

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

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

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

但这不起作用。我试图坚持这个answer使爆炸然后用于每个但也没有工作。这是foreach代码:

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

我错过了什么!

2 个答案:

答案 0 :(得分:1)

它已经解决了。

问题是$popforeach

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

所以在将第一个var重命名为ok之后

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

答案 1 :(得分:1)

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>