Handling errors and continuing execution in PHP script
I don't want to "die()" when it concerns only a small part of the scr开发者_如何学Pythonipt and I tried:
$result = mysql_query($sql) or echo("error with responses");
But it generated an error. How do I just give out an error message and continue to execute the rest of the script since even if it fails to connect, the rest should not be affected.
$result = mysql_query($sql);
if(mysql_error()) {
echo "Error: " . mysql_error();
}
In terms of your original question title - you can't. The purpose of die
and exit
are to terminate script processing. If you don't want to terminate script processing, don't call die
or exit
.
In terms of suppressing the output of errors, this is possible using the error control operator (@
) but in-advisable. (You must check for error state yourself if you're suppressing errors in this manner.)
For example, you could use:
$result = @mysql_query($sql);
if(is_resource($result)) {
// The query worked...
}
else {
// Handle error state, perhaps using mysql_error
}
However, just to make this clear, NEVER casually add the error suppressor to a function call. You MUST ensure you're handling any potential errors correctly yourself.
$result = mysql_query($sql) or print("error with responses");
Echo cannot be used in logical comparisons such as what you're trying to do. You should use print instead, that won't cause PHP errors.
Check the return type of mysql_query
$result = mysql_query($sql);
if ($result===false) {
echo 'The Query failed';
}
//> Continue
You don't have to use die
as the second function call, it's just used as a convention in almost every mysql_query
tutorial out there.
All we're doing is evaluating a boolean expression. $result = $a OR $b
. If the value of $a
is true, then we never execute $b
because we don't need to. We've satisfied the logical OR
with one side of the operator being true, which is all we need.
The die() function immediately exits the script with a message. You could replace it with your own function to print a pretty error message and continue through the script without exiting., e.g:
function my_error_function($status) {
echo "ERROR: $status";
}
$result = mysql_query($sql) or my_error_function("Uhoh. There was a problem executing $sql.");
You can turn off error reporting, which you want to do anyway in a production environment.
error_reporting(0);
It will still throw an error, but it will no longer be shown.
This is very unusual, though. I can't think of a reason why one would want to accept a mySQL error - if the problem is broken SQL, you would usually catch it beforehand.
You should be looking at try / catch not die() or exit
精彩评论