我是PDO
的新手,我正在尝试构建自己的CRUDS应用程序。我已经创建了CRD
,但我对更新用户信息感到困惑。似乎我的语法有问题,但我彻底检查了文档,我无法弄清楚代码有什么问题。它传递给我这个错误:
ERROR: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Doe, email=johndoe@gmail.com, location=New York City WHERE id=1' at line 1
这是我的代码:
include('database.inc.php');
if (isset($_POST['submit'])) {
$id = $_POST['userId']; // 1
$name = $_POST['employee_name']; // John Doe
$email = $_POST['email']; // johndoe@gmail.com
$location = $_POST['location']; // New York City
try {
$query = "UPDATE users SET employee_name=$name, email=$email, location=$location WHERE id=$id";
$statement = $conn->prepare($query);
$statement->execute();
header('Location: ../index.php');
} catch(PDOException $e) {
echo 'ERROR: ' .$e->getMessage();
}
}
答案 0 :(得分:4)
您的代码存在的问题是您没有在SQL中的字符串值周围加引号。但是你应该使用参数化查询,而不是将变量替换为SQL。这解决了引用问题,也阻止了SQL注入。
$query = "UPDATE users SET employee_name=:name, email=:email, location=:location WHERE id=:id";
$statement = $conn->prepare($query);
$statement->execute(array(':name' => $name,
':email' => $email,
':location' => $location,
':id' => $id));
答案 1 :(得分:1)
尝试用单引号(')
包围语句中的变量$query = "UPDATE users SET employee_name='$name', email='$email',
location='$location' WHERE id='$id'";