I was using the following code to make a query with prepared statements: I used mysqli::prepare(), NOT mysqli_stmt::prepare(), so $res does not have to be initialized. It is returned by mysqli::prepared. php.net link
$sql2 = "INSERT INTO best_scores(`user_id`, `test_id`, `score`) VALUES(?, ?, ?)";
if($res = $db->prepare($sql2) == FALSE) echo $db->error . "
";
$res->bind_param("sii", $user_id, $_GET['test'], $max);
$res->execute();
$res->free_result();
When that code was reached, the following error appeared:
Call to a member function bind_param() on a non-object
I looked for answers but all the questions had mistakes in the SQL query string or they didn't free the previous results. None of them helped me, so I tried to change something. I changed my code into this:
$sql2 = "INSERT INTO best_scores(`user_id`, `test_id`, `score`) VALUES(?, ?, ?)";
$res = $db->stmt_init();
if($res->prepare($sql2) == FALSE) echo $db->error . "
";
$res->bind_param("sii", $user_id, $_GET['test'], $max);
$res->execute();
$res->free_result();
Now it is working. But why is it different? What was the problem with the first attempt?
Edit: My $db object is defined like this:
$db = new mysqli("localhost", "user", "pass", "database");
if($db->connect_errno > 0) {
die('Unable to connect to database [' . $db->connect_error . ']');
}