【发布时间】:2016-11-21 22:28:05
【问题描述】:
由于语法错误,无法将数据提交到数据库。
数据库结构
database: red_fungi
username: fungi_47
password: *******
表结构:
列 > 类型
id > int(11)
first_name > text
last_name > text
email > text
phone > text
website > text
description > text
以及php代码:
<?php
$servername = "localhost";
$username = "fungi_47";
$password = "********";
$dbname = "red_fungi";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['first_name']);
$last_name = mysqli_real_escape_string($link, $_POST['last_name']);
$email = mysqli_real_escape_string($link, $_POST['email']);
$phone = mysqli_real_escape_string($link, $_POST['phone']);
$website = mysqli_real_escape_string($link, $_POST['website']);
$comment = mysqli_real_escape_string($link, $_POST['comment']);
$hosting = mysqli_real_escape_string($link, $_POST['hosting']);
$sql = "INSERT INTO contact (id, first_name, last_name, email, phone, website, description, hosting)
VALUES (NULL, $first_name, $last_name, $email, $phone, $website, $comment, $hosting)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
提交的时候看到帖子已经成功了:
first_name=Bill&last_name=Nye&email=bill%40nye.com&phone=8888888888&website=billnyefungi.com&comment=help%20me%20make%20a%20fungi%20website&hosting=yes
但帖子响应显示以下错误:
错误:INSERT INTO 联系人(id、first_name、last_name、电子邮件、电话、网站、描述、托管) VALUES (NULL, , , , , , , )
您的 SQL 语法有错误;检查相应的手册 到您的 MySQL 服务器版本,以便在第 2 行的 ' , , , , , )' 附近使用正确的语法
但是我检查了语法,看不出有什么问题。有什么想法吗?
【问题讨论】:
-
", , , ," 不是有效的 MySQL 语法。
-
至少,您需要在查询中的变量周围添加引号。只需回显您的查询,您就会发现它无效。
-
如果您坚持以这种方式进行查询,您将需要在每个值周围加上引号:
(NULL, '$first_name', '$last_name',...但如果我是您,我不会那样做。 -
谢谢大家。我以为你可以逃脱字符串,它会是安全的。我去看看链接!