簡體   English   中英

將多個復選框保存為php中的不同記錄

[英]saving multiple check-boxes as different records in php

我試圖將多個復選框的結果保存為單獨的記錄。 我的代碼無法正常工作。 請幫忙!

<?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>");
}

?>

結果告訴我什么都沒有添加到數據庫中。

要單獨綁定參數,您可以這樣做:

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中所示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM