Chr*_*ris 1 php mysql prepared-statement
当我运行我准备好的语句时,我收到以下错误:
错误:INSERT INTO文章(
url,headline,pubDate,source,image_loc(?????,,,,))VALUES您的SQL语法错误; 查看与您的MySQL服务器版本对应的手册,以便在第6行使用"?,?,?,?,?)"附近的正确语法
这是似乎抛出错误的代码:
$sql = "INSERT INTO $tableName (`url`,
`headline`,
`pubDate`,
`source`,
`image_loc`)
VALUES(?, ?, ?, ?, ?)";
// MySQLi connection, binds variables to prevent injection, executes
$stmt = $connection->prepare($sql);
$stmt->bind_param('sssss', $url, $headline, $pubDate, $source, $image_loc);
$stmt->execute();
Run Code Online (Sandbox Code Playgroud)
编辑:这是我在单独的文件中设置为我的连接.它起作用的意义是一切都被保存了......我只是在抛出一个错误.
$servername = "localhost";
$username = "xxxxxx";
$password = "xxxxxx";
$dbname = "news";
$tableName = "articles";
$connection = mysqli_connect($servername, $username, $password, $dbname);
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
Run Code Online (Sandbox Code Playgroud)
再次编辑:这是用来检查插入成功的代码,虽然我猜这可能是问题的根源(但我没有足够的经验来理解为什么):
if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection) . "<br>";
}
Run Code Online (Sandbox Code Playgroud)
你的代码:
if (mysqli_query($connection, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection) . "<br>";
}
Run Code Online (Sandbox Code Playgroud)
......用途mysqli_query().这实际上是执行查询的另一种方式,只是不同于execute()它不使用绑定参数.它只是将查询发送到数据库,问号和所有,从而产生您的错误.
如果要检查错误,应execute()在运行时检查语句的结果,而不是执行进一步的查询.$stmt->execute()用这样的东西替换你的行,执行查询并测试成功:
if ($stmt->execute()) {
// Success
} else {
// Failure
}
Run Code Online (Sandbox Code Playgroud)