我正在尝试使用PHP来更新MySQL数据库中的表,但我不断收到以下错误:
错误: 数据库查询失败。您的SQL语法出错;查看与MySQL服务器版本对应的手册 要在'WHERE student_id = 4附近使用正确的语法, student_forename ='Alex',student_surname ='Lee',studen'在线 1。
我想知道更新失败是仅仅是因为语法错误,还是这个问题涉及另一个也许是更严重的问题。这是我的代码:
<?php
$student_id = 4;
$student_forename = 'Alex';
$student_surname = 'Lee';
$student_year = 12;
$query = "UPDATE students SET ";
$query .= "WHERE student_id = {$student_id}, ";
$query .= "student_forename = '{$student_forename}', ";
$query .= "student_surname = '{$student_surname}', ";
$query .= "student_year = {$student_year} ";
$result = mysqli_query( $connection, $query );
//Test if there was a query error
if( $result ) {
echo "Success!";
} else {
die( "Database query failed." . mysqli_error( $connection ) );
}
?>
答案 0 :(得分:2)
将WHERE子句放在最后:
$query = "UPDATE students SET ";
$query .= "student_forename = '{$student_forename}', ";
$query .= "student_surname = '{$student_surname}', ";
$query .= "student_year = {$student_year} ";
$query .= "WHERE student_id = {$student_id}";
这里只需注意一点 - 如果您不使用预先准备好的陈述,您至少应该对您的输入进行消毒。
参见手册:
http://php.net/manual/en/function.filter-var.php
http://php.net/manual/en/filter.filters.sanitize.php
http://php.net/manual/en/filter.filters.validate.php
答案 1 :(得分:1)
如果您查看MySQL UPDATE手册,您会发现忘了SET
部分( - ;
UPDATE [LOW_PRIORITY] [IGNORE] table_reference
SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
答案 2 :(得分:0)
你不是“设置”任何东西。
您的MySQL查询应该设置一些内容:[source]
$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";
您的错误行:
$query = "UPDATE students SET ";