用于更新多行的PDO循环

use*_*177 0 php mysql pdo

我有一个表单,用于检索多行数据,每个项目都有一个textarea,供用户对特定项目进行评论.返回的项目数是可变的,它们不必在任何/所有框中留下注释.

    <textarea name="comment[]" cols="25" rows="2"><?php echo $f2; ?></textarea>
    <input name="tableid[]" type="hidden" value="<?php echo $f1; ?>">
Run Code Online (Sandbox Code Playgroud)

echo语句使用当前存储在数据库中的任何内容填充文本区域,因为用户可以修改其他人输入的内容.

当它传递给表单处理页面时,它返回此..

    Submit: Submit
    comment: Test Comment 1,Test Comment 2
    tableid: 590,591
Run Code Online (Sandbox Code Playgroud)

所以它似乎正确地传递了数组.我正在使用此代码更新数据库

$conn = new PDO("mysql:host=xxxx;dbname=xxxxx",$username,$password);

$i = 0;
if(isset($_POST['submit'])) {
    foreach($_POST['comment'] as $comment) {
                        $comment = $_POST['comment'][$i];

            $id = $_POST['tableid'][$i];
            $stmt = $conn->prepare("UPDATE reservations SET comment=:comment WHERE     tableid=:id");

            $stmt->bindValue(':comment', $comment, PDO::PARAM_INT);
            $stmt->bindValue(':id', $id, PDO::PARAM_INT);

            $stmt->execute();

            $i++;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,这似乎根本没有更新,我哪里错了?

非常感谢

Mad*_*iha 8

一些事情:

  1. 将PDO设置为抛出PDOException错误.它会使调试变得更容易.
  2. 预备语句的要点是,您可以使用不同的变量多次调用它,这样,您只需要准备一次,并多次调用它.你也可以获得很好的性能提升.

码:

//New try/catch block to catch PDOExceptions should they arise.
try {
    $conn = new PDO("mysql:host=xxxx;dbname=xxxxx", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //Set PDO to fire PDOExceptions on errors.
        PDO::ATTR_EMULATE_PREPARES => false //Disable emulated prepares. Solves some minor edge cases.
    ]);

//No need for incrementer. The index of the comment should be enough.
    if (isset($_POST['submit'])) {
        //Note the prepare on the outside.
        $stmt = $conn->prepare("UPDATE `reservations` SET `comment` = :comment WHERE `tableid` = :id");
        //As well as the binding. By using bindParam, and supplying a variable, we're passing it by reference.
        //So whenever it changes, we don't need to bind again.
        $stmt->bindParam(":comment", $comment, PDO::PARAM_STR);
        $stmt->bindParam(":id", $id, PDO::PARAM_INT);

        foreach ($_POST['comment'] as $index => $comment) {

            //All that's left is to set the ID, see how we're reusing the $index of the comment input?

            $id = $_POST['tableid'][$index];

            $stmt->execute();

        }
    }
} catch (PDOException $e) {
    echo "Some sort of error has occurred! Here are the details! ";
    echo $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)