动态更新mysql表

时间:2015-02-02 22:56:00

标签: php mysql

我正在尝试动态更新表格

$QUERY = "UPDATE `internshala`.`student` SET `High_School` = \'$High_School\', `HS_Percentage` = \'$HS_Percentage\', `Intermediate` = \'$Intermediate\', `I_Percentage` = \'$I_Percentage\', `Graduation` = \'$Graduation\', `G_Score` = \'$G_Score\', `G_Year` = \'$G_Year\', `PG_Year` = \'$PG_Year\', `PostGraduation` = \'$PostGraduation\', `PG_Score` = \'$PG_Score\' WHERE `student`.`id` = '$_SESSION['user_id'];";

抛出错误syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

我无法找到正确的语法,上面使用的语法是我从phpmyadmin推断的。

PS:update语句中使用的所有变量都设置为非空值。

1 个答案:

答案 0 :(得分:2)

您的查询存在很多问题。您在使用双引号定义字符串时转义单引号。你不需要这个。

SET `High_School` = \'$High_School\',

应该阅读

SET `High_School` = '$High_School',

此外,您在最后使用会话变量而不是关闭引用

WHERE `student`.`id` = '$_SESSION['user_id'];";

您需要将数组项括在花括号中并关闭单引号:

WHERE `student`.`id` = '{$_SESSION['user_id']}';";

您的完整查询应如下所示

$QUERY = "UPDATE `internshala`.`student` SET 
  `High_School` = '$High_School', 
  `HS_Percentage` = '$HS_Percentage', 
  `Intermediate` = '$Intermediate',
  `I_Percentage` = '$I_Percentage',
  `Graduation` = '$Graduation',
  `G_Score` = '$G_Score', 
  `G_Year` = '$G_Year', 
  `PG_Year` = '$PG_Year', 
  `PostGraduation` = '$PostGraduation', 
  `PG_Score` = '$PG_Score' 
 WHERE `student`.`id` = '{$_SESSION['user_id']}';";

也不要使用此方法。您对sql注入持开放态度。你真的应该使用PDO或mysqli准备好的语句。看一下这篇文章:How can I prevent SQL injection in PHP?