首页  >  文章  >  后端开发  >  如何使用 PHP 准备语句进行安全数据库更新?

如何使用 PHP 准备语句进行安全数据库更新?

Susan Sarandon
Susan Sarandon原创
2024-10-21 19:58:29140浏览

How to Use PHP Prepared Statements for Secure Database Updates?

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

避免 SQL 注入

执行数据库查询时,准备语句对于防止SQL注入。它们允许您动态地将数据插入到查询中,而不会影响安全性。

更新单个字段

在您的代码片段中,您仅更新一个字段:内容。这是可以接受的,因为您可以有选择地更新 UPDATE 语句中的各个列。

正确的参数绑定

要在准备好的语句中正确绑定参数,必须确保代码中的数据类型与 MySQL 语句中的数据类型相匹配。在您的例子中,您有:

<code class="php">$stmt = $this->mysqli->prepare("UPDATE datadump SET content=? WHERE id=?");
$stmt->bind_param('is', $id, $content);</code>

bind_param() 方法中的“is”指定您要绑定一个整数 (i) 和一个字符串 (s)。但是,您实际上使用以下代码来设置内容变量:

<code class="php">$content = isset($_POST['content']) ? $this->mysqli->real_escape_string($_POST['content']) : '';</code>

它返回一个字符串。这种不匹配可能会导致错误。

更正:

要更正此问题,请进行以下更改:

<code class="php">if ($stmt === false) {
  trigger_error($this->mysqli->error, E_USER_ERROR);
  return;
}

$content = $_POST['content'] ?: '';
$stmt->bind_param('si', $content, $id);
````
**Additional Notes:**

* Always remember to check for statement preparation errors using `if ($stmt === false)`.
* Bind your parameters in the same order as they appear in your SQL statement.

**Troubleshooting:**

If you're still facing issues, ensure that:

* Your MySQL connection is established correctly.
* The table and column names in your statement are spelled correctly.</code>

以上是如何使用 PHP 准备语句进行安全数据库更新?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn