SQL语法错误 - ' '','',now())'

时间:2015-02-27 06:52:47

标签: php mysql string int

我正在尝试在数据库中插入一行,并且我得到以下错误。

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 ' '', '', now())' at line 1.

如果我在$gradeid之外使用单引号,它将转换为字符串,因为我的数据库列是整数,它也是外键,即使这会因以下错误而失败

Cannot add or update a child row: a foreign key constraint fails (`mydb`.`mytable1`, CONSTRAINT `activitygoalmaster_ibfk_1` FOREIGN KEY (`intGradeID`) REFERENCES `mytable2` (`intGradeID`))

我不知道错误是什么?可能是一些简单的错误,但我没有得到它。请帮忙。我在php中的代码是

  $title = $_POST['Title'];
  $gradeid = $_POST['GradeID'];
  $masterimgpath = $_POST['MasterImgPath'];
  $description = $_POST['Description'];

  $sql = "INSERT INTO activitygoalmaster(vchTitle, intGradeID, vchMasterImgPath, vchDescription, dtCreatedAt)VALUES('$title', $gradeid, '$masterimgpath', '$description', now())";
  $result = mysql_query($sql);

3 个答案:

答案 0 :(得分:3)

看起来gradeid为空。尝试验证它。

不要使用mysql-*函数,因为这已被弃用。使用mysqli_*或pdo准备好陈述。

答案 1 :(得分:0)

请检查表格结构及其价值。

在执行之前打印你的$ sql。所以你很容易发现错误。

答案 2 :(得分:0)

我有一个问题: intGradeID列是int()对吗?是varchar()吗?如果它是varchar(),则它确实需要insert查询中的单引号。

要使用a foreign key constraint fails解决错误,请先将mytable2 grade id插入mytable1,然后再将其插入foreign key。它会显示此错误,因为mytable1上的{{1}}需要此错误。