使用PDO循环更新多行数据
P粉384366923
P粉384366923 2023-10-24 09:38:58
0
2
707

我有一个可检索多行数据的表单,每个项目都有一个文本区域,供用户对特定项目发表评论。返回的项目数量是可变的,并且他们不必在任何/所有框中留下评论。

<textarea name="comment[]" cols="25" rows="2"><?php echo $f2; ?></textarea>
    <input name="tableid[]" type="hidden" value="<?php echo $f1; ?>">

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

当它被传递到表单处理页面时,它会返回这个..

Submit: Submit
    comment: Test Comment 1,Test Comment 2
    tableid: 590,591

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

$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++;
    }
}

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

非常感谢

P粉384366923
P粉384366923

全部回复(2)
P粉704066087

几件事:

  1. 将 PDO 设置为在出现错误时抛出 PDOException。这将使调试变得更加容易。
  2. 准备好的语句的要点是,您可以使用不同的变量多次调用它,这样,您只需要准备一次,然后多次调用它。您也可以从中获得不错的性能提升。

代码:

$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();

        }
    }
P粉994092873

雷雷

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!