”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何解决 PHP 准备语句数据库更新中参数顺序不正确的问题?

如何解决 PHP 准备语句数据库更新中参数顺序不正确的问题?

发布于2024-11-08
浏览:698

How to Resolve Incorrect Parameter Order in PHP Prepared Statement Database Updates?

用于数据库更新的 PHP 准备语句

本次讨论的重点是如何正确利用 PHP 中的准备语句来防止 SQL 注入等漏洞。相关代码块的目的是使用准备好的语句更新具有单个字段的数据库表。

在提供的代码中,class.Scripts.inc 文件中的 update() 方法使用准备好的语句语句尝试更新数据转储表。但是,由于bind_param()方法期间参数顺序不正确,执行不成功。当前代码按照 $id 和 $content 的顺序绑定参数,而 SQL 语句期望它们以相反的顺序,导致记录标识不正确并且影响零行。

下面更正的代码纠正了这个问题通过以正确的顺序绑定参数并提供额外的错误处理来防止错误:

$stmt = $this->mysqli->prepare("UPDATE datadump SET content=? WHERE id=?");
/* Always check whether the prepare() succeeded */
if ($stmt === false) {
    trigger_error($this->mysqli->error, E_USER_ERROR);
    return;
}

$id = 1;
/* Bind our params */
/* Bind variables in the same order as SQL params */
$stmt->bind_param('si', $content, $id);

/* Set our params */
/* No escaping needed when using prepared statements */
$content = $_POST['content'] ?: '';

/* Execute the prepared Statement */
$status = $stmt->execute();
/* Always check whether the execute() succeeded */
if ($status === false) {
    trigger_error($stmt->error, E_USER_ERROR);
}

printf("%d Row inserted.\n", $stmt->affected_rows);

关于您的具体查询:

  1. 您遇到的“0 Rows Inserted”消息是由于到相反的参数顺序。 id和content参数绑定的顺序不正确,导致WHERE子句匹配不到任何行。
  2. 更新表时,只修改需要的字段是可以接受的。表中其他列保持不变。
版本声明 本文转载于:1729512196如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3