我已经尝试搜索forumn但是在编写我的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
// }
?>
这是我收到的错误
可捕获的致命错误:
mysqli_stmt类的对象无法在中转换为字符串 /Applications/XAMPP/xamppfiles/htdocs/z_admin/submit_data.php 在线 19
任何帮助或指示将不胜感激。谢谢
答案 0 :(得分:1)
重写您的代码
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";
此方法添加了您可以想象的最佳错误检查。
答案 1 :(得分:0)
不要在此行中回显$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";
}