gpt4 book ai didi

php - 尝试将文本字段中的数据插入数据库时​​出现 MySQL 错误

转载 作者:行者123 更新时间:2023-11-29 04:33:30 26 4
gpt4 key购买 nike

尝试从我的网站向我的数据库插入数据时出现此错误:

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();
?>

不确定我在这里做错了什么?

最佳答案

这是一个准备好的语句,所以你需要准备它,绑定(bind)你的值,然后然后执行它:

$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 函数按原样执行代码,没有任何更改。

关于php - 尝试将文本字段中的数据插入数据库时​​出现 MySQL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51902267/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com