尝试将数据从我的网站插入数据库时出现此错误:
Error: INSERT INTO newtask (new_category, new_department, new_required,
new_name, new_address, new_contact, new_email, new_logged, new_description)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
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 '?, ?, ?, ?, ?, ?, ?,
?,
?)' at line 1
这是我的代码:
<?php
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'tasks_db';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO newtask (new_category, new_department, new_required,
new_name, new_address, new_contact, new_email, new_logged, new_description)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
不确定在这里我在做什么错吗?
答案 0 :(得分:4)
这是一条准备好的语句,因此您需要准备它,绑定值并然后执行它:
$stmt = $conn->prepare("INSERT INTO newtask (new_category, new_department, new_required,
new_name, new_address, new_contact, new_email, new_logged, new_description)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
// One "s" per placeholder value, plus one value per "s" after
$stmt->bind_param("sssssssss", $new_category, $new_department, ...);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$new_category
的值就是该列中要输入的值,依此类推。
the documentation涵盖了所有内容。
错误是您试图运行带有占位符值且无数据的SQL查询。 ?
在MySQL中不是有效值。在驱动程序级别,用bind_param
生成的语句的prepare
操作已将其替换。 query
函数按原样执行代码。