我正在尝试制作一个令人难以置信的基本形式,将名字,姓氏和年龄添加到名为Test的非常基本的数据库中。这是我的HTML代码:
<html>
<head>
</head>
<body>
<h1>Welcome!</h1>
<br>
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>
<input type="submit">
</form>
</body>
</body>
</html>
这是我的PHP代码,隐藏了数据库名称,主机和登录信息:
<?php
$con=mysqli_connect("HOST","USER","PASS","DB");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql= "INSERT INTO Test ('First Name', 'Last Name', 'Age')
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
当我在表单中输入数据并提交时,这是我的错误。我被引导到这个页面:
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 ''First Name', 'Last Name', 'Age') VALUES ('Robert','Maxwell','18')' at line 1
答案 0 :(得分:3)
更改
$sql= "INSERT INTO Test ('First Name', 'Last Name', 'Age')
代表
$sql= "INSERT INTO Test (`First Name`, `Last Name`, `Age`)
- )
答案 1 :(得分:1)
您的查询不正确,您的列表中没有空格 - 它们必须是驼峰式(FirstName)或下划线(first_name)
$sql= "INSERT INTO Test (`First_Name`, `Last_Name`, `Age`)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
或
$sql= "INSERT INTO Test (`FirstName`, `LastName`, `Age`)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
注意:请勿在生产中使用,否则会泄露您的查询。考虑保护您的查询免受SQL注入。