嗨,我正在尝试学习使用预准备语句的正确方法,以避免SQL注入等.
当我执行脚本时,我从我的脚本中得到一条消息,说0行已插入,我希望这可以说1行插入,当然更新表.我对我准备好的陈述并不完全确定,因为我做了一些研究,我的意思是它因例子而异.
当我更新我的表时,我需要声明所有字段还是只更新一个字段?
任何信息都会非常有用.
的index.php
require("classes/class.Scripts.inc");
$insert = new Scripts();
$insert->read();
$insert->update();?>
类/ class.Scripts.inc
public function update() {
if (isset($_POST['update'])) {
$stmt = $this->mysqli->prepare("UPDATE datadump SET content=? WHERE id=?");
$id = 1;
/* Bind our params */
$stmt->bind_param('is', $id, $content);
/* Set our params */
$content = isset($_POST['content']) ? $this->mysqli->real_escape_string($_POST['content']) : '';
/* Execute the prepared Statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
}
}
解决方法:
$stmt = $this->mysqli->prepare("UPDATE datadump SET content=? WHERE id=?");
/* BK: always check whether the prepare() succeeded */
if ($stmt === false) {
trigger_error($this->mysqli->error, E_USER_ERROR);
return;
}
$id = 1;
/* Bind our params */
/* BK: variables must be bound in the same order as the params in your SQL.
* Some people prefer PDO because it supports named parameter. */
$stmt->bind_param('si', $content, $id);
/* Set our params */
/* BK: No need to use escaping when using parameters, in fact, you must not,
* because you'll get literal '\' characters in your content. */
$content = $_POST['content'] ?: '';
/* Execute the prepared Statement */
$status = $stmt->execute();
/* BK: always check whether the execute() succeeded */
if ($status === false) {
trigger_error($stmt->error, E_USER_ERROR);
}
printf("%d Row inserted.\n", $stmt->affected_rows);
回答你的问题:
I get a message from my script saying 0 Rows Inserted
这是因为您在绑定参数时反转了参数的顺序.所以你在id列中搜索$content的数值,这可能被解释为0.所以UPDATE的WHERE子句匹配零行.
do I need to declare all the fields or is it ok to just update one field??
在UPDATE语句中只设置一列是可以的.其他列不会更改.
标签:php,mysqli,prepared-statement,sql-update
来源: https://codeday.me/bug/20190923/1814005.html