解决上一个问题(Insert Query returns true but does not work)后,我的查询运行并成功插入数据库。作为一个快速的提示:我创建了两个下拉菜单,用户可以选择一个员工和一个班级组,并将此人分配到所选的班级。然而,每次运行它都会引发错误(这是一个我无法解释的错误):
Invalid query: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 '1' at line 1
但是,当我再次运行查询时,我收到此消息:
Duplicate entry '5833977-58339492' for key 'PRIMARY'
我绝对相信我没有尝试使用已经存在的教师/类组合运行此查询,因此清楚地告诉我,即使查询导致错误消息,也已成功进入数据库。我有什么办法可以防止这种错误发生吗?下面我添加了我的查询代码供你们查看,看看你的想法(暂时忽略mysql而不是mysqli,我只是想在我改编之前先创建它):
// The variables from the previous page //
$teacher = $_POST['teacher'];
$class = $_POST['class'];
// The MySQL variables that we need to use in the query //
$idStaff = mysql_result(mysql_query("SELECT DISTINCT idStaff from $table_name WHERE Staff =
'$teacher'"), 0);
$idClass = mysql_result(mysql_query("SELECT DISTINCT idClass from $table_name WHERE Class =
'$class'"), 0);
// Query to insert data into the staffclass table //
$query_addteacher = mysql_query("INSERT INTO Staffclass (idStaff, idClass)
VALUES ('$idStaff', '$idClass')") or die(mysql_error());
$result = mysql_query($query_addteacher);
if (!$result)
{
die('Invalid query:' . mysql_error());
}
else
{ echo "Success!";
header("location:addteachertest.php"); }
请注意,如果查询返回NOT FALSE,它也不会重定向到位置页面,如标题中所示。