我尝试搜索论坛,但在编写 php 准备好的语句时无法修复 fatal error 。
我使用准备好的语句来防止 SQL 注入(inject),并防止用户输入撇号时出现错误。下面是我的代码:
提交数据.php
<?php
include "../connect.php";
$message_form = $_POST['message'];
$username_form = $_POST['user'];
// $insert_data=$db->query("INSERT INTO test_table_1(message,user) VALUES ('$message_form','$username_form')");
$insert_data=$db->prepare("INSERT INTO test_table_1(message,user) VALUES (?, ?)");
$insert_data->bind_param("ss", $message_form, $username_form);
$insert_data->execute();
if ($insert_data === TRUE ){
echo "New record created successfully";
} else {
echo "Error: " . $insert_data . "<br>" . $db->error;
}
$insert_data->close();
$db->close();
?>
我的数据库连接文件(connect.php)
<?php
$host = "localhost";
$user = "root";
$pass = "";
$database_name = "test";
$table_name = "test_table_1";
//connect to mysql database
$db = new mysqli($host, $user, $pass, $database_name);
//check connection
if ($db -> connect_error) {
die("error mysql database not connected: " . $db -> connect_error);
}
// else {
// echo "connected successfully" ; //enable this for debugging purpose
// }
?>
这是我收到的错误
Catchable fatal error:
Object of class mysqli_stmt could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/z_admin/submit_data.php on line 19
任何帮助或指示将不胜感激。谢谢
最佳答案
不要在这一行中回显$db->error
,因为它包含数据库连接的对象
echo "Error: " . $insert_data . "<br>" . $db->error;
改为使用affected_rows
返回上次查询中使用的自动生成的ID
if ($insert_data->affected_rows >0){
echo "New record created successfully";
} else {
echo "Not inserted";
}
关于使用 mysqli_stmt 时 PhP 可捕获的 fatal error ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32629538/