由于语法错误而无法将数据提交到数据库。
数据库结构
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行的',,,,,)附近使用正确的语法
但是我检查了语法,看不出有什么问题。任何想法出了什么问题?
答案 0 :(得分:2)
您的sql语句需要看起来更像这样:
$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}')";
当我遇到这样的问题时,我做的第一件事是回显sql,看看是否有明显的问题
并跟进所有数据验证&amp;其他用户提出的安全点。
答案 1 :(得分:1)
您的代码假设将填充$ _POST [&#39; XXX&#39;],并且它不是。这就是所有那些,,,,,,,,在错误中的意思。
相反,首先检查是否创建了$ _POST [&#39; XXX&#39;],并且在使用之前有一个值。
if ((isset($_POST['first_name'])) && (!empty( $_POST['first_name'])) ) {
//do query and rest of your script
} else { die('Need form input');}