Reputation: 15
I'm trying to figure out exactly how I should work around this. When I have one MySQLi query fail, it automatically kills the rest of the script. For instance
//Pure example code
$data = $mysqli->prepare("somequery");
$data->execute(); // Execute the prepared query.
//If the query above fails, the rest of the script doesn't get executed.
Basically, I'm trying to figure out how I can stop PHP from killing the script when the query fails. Any ideas? I moved to prepared statements because of the supposed performance and security gains. It'd be a pain to rewrite everything to plan old queries.
Thanks,
Upvotes: 0
Views: 651
Reputation: 272106
PHP kills scripts on fatal errors. If this line fails:
$data = $mysqli->prepare("somequery");
PHP will not kill your script but $data
is set to false. The script will be killed upon the next line:
$data->execute();
With the following error:
Fatal error: Call to a member function execute() on a non-object in...
First of all, you need to enable error_reporting
so that you could be able to diagnose the problem (and perhaps figure out the solution) yourself. Secondly, as @meagar mentioned, check for return values of mysqli functions:
$data = $mysqli->prepare("somequery");
if($data === false) {
echo $mysqli->error;
// dying isn't the most graceful approach by the way
die();
}
if($data->execute() === false) {
echo $mysqli->error;
die();
}
Changing from mysql_* to mysqli has nothing to do with your issue. If you were using mysql_* you still need to check the return values from functions. A generic rule: never assume that your queries will always succeed.
Upvotes: 1
Reputation: 2970
if($data = $mysqli->prepare("somequery")) {
// binding
$data->execute(); // Execute the prepared query.
}
From the documentation
Upvotes: 0
Reputation: 239311
You need to actually check for success, rather than blindly executing $data->execute()
when data
may be false
, which will raise an error and abort your script.
From the docs, prepare
...
returns a statement object or FALSE if an error occurred.
Upvotes: 3