在构建我的应用程序时,我毫无问题地进行了创建查询。但是,当我将 PHP 从创建文件复制到更新文件时,我收到此错误:
UPDATE people SET firstname = 'First', lastname = 'Last', email = 'test@mail.com', phonenumber = 1234567890 WHERE id = 1'
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''' at line 1
通常,当我收到此错误时,该错误会为我提供准确的修复位置。谁能帮我找到这个错误?
更新.sql:
if (isset($_POST['submit'])) {
require "../resources/config.php";
require "../resources/common.php";
try {
$connection = new PDO($dsn, $username, $password, $options);
$id = $_GET['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phonenumber = $_POST['phonenumber'];
$updated_number = array($firstname, $lastname, $email, $phonenumber);
$sql = sprintf(
"UPDATE %s SET firstname = '$firstname', lastname = '$lastname', email = '$email', phonenumber = $phonenumber WHERE id = %s",
"people",
$id
);
$statement = $connection->prepare($sql);
$statement->execute($updated_number);
header("Location: index.php");
}
catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
最佳答案
您这里有两个问题。第一个,也是更重要的是您对准备好的语句的使用。查询本身中的所有值都应该被绑定(bind)。所以你的查询实际上应该是:
$updated_number = array($firstname, $lastname, $email, $phonenumber, $id);
$sql = sprintf("UPDATE %s
SET firstname = ?, lastname = ?, email = ?, phonenumber = ?
WHERE id = ?",
"people");
第二个是您的 sprintf
用法。
WHERE id = %s
%s
是一个字符串,%d
是一个整数。如果有正确的准备好的语句,则不需要这样做。如果 "people"
不是变量并且是动态构建的,我认为将整个查询构建为普通字符串会更容易。例如
$sql = 'UPDATE people
SET firstname = ?, lastname = ?, email = ?, phonenumber = ?
WHERE id = ?';
关于php - PHP/MySQL 中的更新查询失败,错误代码 1064,SQLState 42000,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49719057/