【问题标题】:saving multiple check-boxes as different records in php在php中将多个复选框保存为不同的记录
【发布时间】:2015-06-11 22:56:58
【问题描述】:

我正在尝试将多个复选框的结果保存为单独的记录。我的代码不起作用。请帮忙!

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

?>

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

【问题讨论】:

  • 你没有绑定任何东西。
  • 我戒掉了会绑定 Ralph 的东西。,但你应该始终绑定你的查询值,对 @Fred-ii-
  • 你是 Sam - @JayBlanchard
  • 您收集受影响的行数的方式有点奇怪,因为您期望“true”返回“1”。这里的行为可能不是那么一致。
  • 请问,你建议我如何解决这个问题?对 PDO 非常陌生。。谢谢

标签: php html mysql pdo


【解决方案1】:

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

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 中所示的数组

【讨论】:

  • 请检查我在下面插入的代码。它没有保存到数据库中
  • 您需要在代码中添加一些错误检查@anelka。您不知道您的查询或连接是否正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-31
  • 1970-01-01
  • 1970-01-01
  • 2017-10-11
相关资源
最近更新 更多