PhP 使用 mysqli_stmt 时可捕获的致命错误

PhP catchable fatal error when using mysqli_stmt

我曾尝试搜索论坛,但在编写 php 准备好的语句时无法修复我的致命错误。

我正在使用准备好的语句来防止 sql 注入,并防止用户输入撇号时出错。下面是我的代码:

submit_data.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

任何帮助或指点将不胜感激。谢谢

重写你的代码

connect.php

<?php
$host = "localhost";
$user = "root";
$pass = ""; 

$database_name = "test"; 
$table_name = "test_table_1";  

//connect to mysql database
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db = new mysqli($host, $user, $pass, $database_name); 

submit_data.php

<?php
include "../connect.php";

$stmt=$db->prepare("INSERT INTO test_table_1(message,user) VALUES (?, ?)");

$stmt->bind_param("ss", $_POST['message'], $_POST['user']);
$stmt->execute();
echo "New record created successfully";

此方法添加了您想象不到的最佳错误检查。

不要在这一行回显 $db->error 因为它包含你的数据库连接对象

echo "Error: " . $insert_data . "<br>" . $db->error;

而是使用 affected_rows Returns 上次查询中使用的自动生成的 ID

if ($insert_data->affected_rows >0){
    echo "New record created successfully";

} else {
    echo "Not inserted";
  }