Syntax Error with MySQL Query

淺唱寂寞╮ 提交于 2019-12-25 07:06:12

问题


I am getting the following error and I have spent hours looking at it and cannot figure out why!

ERROR: 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 'primary='doej2', secondary='1' WHERE id='2'' at line 1

Here is my code:

<?php
if (isset($_POST[Edit])){

$id = $_POST['id'];
$primary = $_POST['primary'];
$secondary = $_POST['secondary'];

$query = mysql_query("UPDATE eventcal SET primary='$primary', secondary='$secondary' WHERE id='$id'");

if (!$query) {
  $_SESSION['alert'] = 'ERROR: ' . mysql_error();
}

}?>

And here is my table structure for eventcal table:

 CREATE TABLE `eventcal` (
 `id` int(10) unsigned NOT NULL auto_increment,
 `region` tinyint(3) unsigned NOT NULL,
 `primary` varchar(25) NOT NULL,
 `secondary` tinyint(1) NOT NULL,
 `eventDate` date NOT NULL,
 PRIMARY KEY  (`id`),
 KEY `primary_2` (`primary`),
 KEY `secondary` (`secondary`),
 CONSTRAINT `eventcal_ibfk_1` FOREIGN KEY (`primary`) REFERENCES `users` (`username`) ON UPDATE CASCADE
 ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

Can anyone see what I'm missing? Thanks!


回答1:


"primary" is a reserved word in MySQL. You can put ticks around it to properly use it (as well as the other fields:

$query = mysql_query("UPDATE `eventcal` SET `primary`='$primary', `secondary`='$secondary' WHERE `id`='$id'");



回答2:


'primary' is a MySQL reserved word. From the documentation:

Reserved words are permitted as identifiers if you quote them as described in Section 8.2, “Schema Object Names”.




回答3:


Worse than the syntax error is the SQL-injection hole:

Change this:

coding horror
$id = $_POST['id'];
$primary = $_POST['primary'];
$secondary = $_POST['secondary'];

Into this code

$id = mysql_real_escape_string($_POST['id']);
$primary = mysql_real_escape_string($_POST['primary']);
$secondary = mysql_real_escape_string($_POST['secondary']);


来源:https://stackoverflow.com/questions/1128613/syntax-error-with-mysql-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!