将多个复选框保存为php中的不同记录

时间:2015-06-11 13:05:59

标签: php html mysql pdo

我试图将多个复选框的结果保存为单独的记录。我的代码无法运行。请帮忙!

<?php

session_start();
$id = $_SESSION['user_id'];
$db = new PDO('mysql:host=localhost;dbname=idp;charset=utf8','root', '');

foreach($_POST['comp'] as $val){
    $tmp['user_id'] = $id;
    $tmp['comp_id'] = $val;
    $vars[] = $tmp;
}

$qry = "INSERT INTO compentency_result (user_id, result) VALUES (:user_id, :comp_id)";

try
{
    $sql = $db->prepare($qry);
    $numRows = 0;
    foreach($vars as $insert){
        $numRows += $sql->execute($insert);
    }
    print("<p>There were {$numRows} inserted into the database!</p>");
}
catch(PDOException $e)
{
    print("<p>Oops! There was an issue - this is the message: {$e->getMessage()}</p>");
}

?>

结果显示数据库中没有添加任何内容。

1 个答案:

答案 0 :(得分:3)

要单独绑定参数,您可以这样做:

try
{
    $sql = $db->prepare($qry);
    $numRows = 0;
    foreach($vars as $insert){
        $sql->bindParam(':user_id', $insert['user_id'], PDO::PARAM_STR);
        $sql->bindParam(':comp_id', $insert['comp_id'], PDO::PARAM_STR);
        $sql->execute();
        $numRows += $sql->rowCount(); // get the rows affected this way
    }
    echo "<p>There were {$numRows} inserted into the database!</p>";
}

此外,我使用rowCount()添加了更合适可靠的获取受影响行的方法。

如果您不想单独绑定元素,可以将execute()与数组一起使用,如Demystifying PDO

所示