Reputation: 105
I have tried searching the forumn but could not fix my fatal error when coding my php prepared statement.
Im using a prepared statement to prevent sql injection and also prevent error when user inputs apostrophe. Below is my code:
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();
?>
my connection file to the database( 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
// }
?>
This is the error i am receiving
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
Any help or pointers will be greatly appreciated. Thank you
Upvotes: 0
Views: 94
Reputation: 157839
Rewrite your code as this
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";
This method adds best error checking you can ever imagine.
Upvotes: 1
Reputation: 22532
Don't echo $db->error
in this line because it contain object of your database connection
echo "Error: " . $insert_data . "<br>" . $db->error;
Instead Use affected_rows
Returns the auto generated id used in the last query
if ($insert_data->affected_rows >0){
echo "New record created successfully";
} else {
echo "Not inserted";
}
Upvotes: 1