在构建我的应用程序时,我毫无困难地进行了创建查询。但是,当我将PHP从创建文件复制到更新文件时,我一直收到此错误:
UPDATE people SET firstname ='First',lastname ='Last',email = 'test@mail.com',phonenumber = 1234567890 WHERE id = 1'
SQLSTATE [42000]:语法错误或访问冲突:1064您有 SQL语法错误;查看与您的手册相对应的手册 MariaDB服务器版本,在第1行的'''附近使用正确的语法
通常,当我收到此错误时,错误会给我一个准确的修复位置。任何人都可以帮我找到这个错误吗?
update.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();
}
}
答案 0 :(得分:1)
这里有两个问题。第一个,更重要的是你使用预备语句。应绑定查询本身中的所有值。所以你的查询应该是:
$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"
不是变量并且是动态构建的,我认为将整个查询构建为普通字符串会更容易。 e.g。
$sql = 'UPDATE people
SET firstname = ?, lastname = ?, email = ?, phonenumber = ?
WHERE id = ?';
答案 1 :(得分:1)
不要使用sprintf
构建SQL语句,因为它会将代码打开到SQL注入攻击,最好使用看起来像这样的预处理语句:
$sql = "UPDATE `people` SET `firstname` = :firstname, `lastname` = :lastname, `email` = :email, `phonenumber` = :phonenumber WHERE `id` = :id;"
$statement = $connection->prepare($sql);
$statement->bindParam(':firstname', $firstname);
$statement->bindParam(':lastname', $lastname);
$statement->bindParam(':email', $email);
$statement->bindParam(':phonenumber', $phonenumber);
$statement->bindParam(':id', $id);