同时自学SQL和PHP并收到此错误:
错误:您的SQL语法出错;查看与您的MySQL服务器版本对应的手册,以便在'姓名,姓氏,课程_id,教授'附近使用正确的语法('duke','john','doe','cpsc','老师'在线) 1查询
我的代码应该从表单中获取信息并将其插入到我已经创建的数据库中,我已经查看了几个小时并且已经搜索了一段时间的互联网,但仍然找不到什么导致这个。任何人都可以帮助我吗?
这是我的test.php文件,其中包含以下表单:
<html>
<head>
<title>Insert data into database</title>
</head>
<body>
<form method="post" action="handler.php">
<p>What is your University:</p>
<input type="text" name="uni"><br>
<p>What is your First Name:</p>
<input type="text" name="f_name"><br>
<p>What is your Last Name:</p>
<input type="text" name="l_name"><br>
<p>What is your Course:</p>
<input type="text" name="cou_id"><br>
<p>Who was your Professor for that course?:</p>
<input type="text" name="pro_id"><br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
这是我的handler.php文件,它将表单中的信息存储到数据库中:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$uni = $_POST['uni'];
$uni= mysql_real_escape_string($uni);
$f_name = $_POST['f_name'];
$f_name = mysql_real_escape_string($f_name);
$l_name = $_POST['l_name'];
$l_name = mysql_real_escape_string($l_name);
$cou_id = $_POST['cou_id'];
$cou_id = mysql_real_escape_string($cou_id);
$pro_id = $_POST['pro_id'];
$pro_id = mysql_real_escape_string($pro_id);
$con = mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("tester") or die(mysql_error());
if (!mysql_query("INSERT INTO my_hw (University, First Name, Last Name, Course_id, Professor) VALUES ('$uni','$f_name','$l_name','$cou_id','$pro_id')"))
{
die('Error: ' . mysql_error() . " with query ". $sql);
}
echo "1 record added";
mysql_close($con);
?>
</body>
</html>
由于
答案 0 :(得分:1)
您的名字和姓氏列中有空格:
INSERT INTO my_hw (University, `First Name`, `Last Name`, Course_id, Professor) VALUES ('$uni','$f_name','$l_name','$cou_id','$pro_id')
注意添加的反引号。
答案 1 :(得分:0)
更改列名,使其没有空格。在列名中包含空格是不好的做法。
答案 2 :(得分:0)
由于您使用的是mysql
,因此列名必须用反引号分隔,而不是单引号,因为它们之间包含空格,
INSERT INTO my_hw (University, `First Name`, `Last Name`,...