php - MySQL更新语法错误

标签 php mysql

<分区>

我正在使用 php 对数据库运行基本更新,但我遇到了 SQL 语法错误,而且我一辈子都看不出哪里出了问题。数据库中的字段称为订单,它设置为 int(8)。我尝试将其更改为 smallint 和 varchar,增加了但没有快乐。我也尝试修改查询中的 ' 和 "。代码如下......

    $query = "UPDATE gigs SET order='$order' WHERE gig_id='$id'";
    if ($r = mysql_query($query) ) {
        echo  "<p>UPDATED:" . $row['year'] ." - " . $row['month'] . " - " .  $row['day'] . " = $order</p>";
    } else {
        echo "<p>" . mysql_error() . "<br />$q</p>";
    }

$order 是年月日值组合成一个整数值,例如2013 年 4 月 12 日 = 20130412。

这是我得到的错误信息

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 'order='20040802' WHERE gig_id='10'' at line 1 UPDATE gigs SET order='20040802' WHERE gig_id='10'

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 'order='20040804' WHERE gig_id='11'' at line 1 UPDATE gigs SET order='20040804' WHERE gig_id='11'

最佳答案

ORDER 是保留关键字。为了语句不抛出异常,需要用反引号对列进行转义,

UPDATE gigs SET `order` = '$order' WHERE gig_id = '$id'

作为旁注,查询易受 SQL Injection 攻击如果变量的值(s) 来自外部。请查看下面的文章,了解如何预防它。通过使用 PreparedStatements,您可以摆脱在值周围使用单引号。

关于php - MySQL更新语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15977743/

相关文章:

php - 我怎样才能停止 php while 循环一遍又一遍?

php/mysql 将州附加到城市

mysql - 使用外键连接表

php - 在 PHP mysql_query() 中一次运行两个 MySQL 查询

mysql - 如何在Django中自动切换多个数据库服务器?

php - 我正在尝试将 docker 用于带有 nginx 的 php5.6,但配置存在问题

php - Google App Engine Cloud SQL 上的 SQL 语法错误

mysql - 使用设置值数组通过 myCon.query 更新表

php - 我想使用 php 从数据库中删除我单击的记录

php - 如何在java脚本onclick标识符中安全地回显php字符串