Error handling and continued execution in a PHP script

I don't want "die ()" when it comes to just a small part of the script, and I tried:

$result = mysql_query($sql) or echo("error with responses"); 

But he made a mistake. How do I just give an error message and continue to execute the rest of the script, since even if it cannot connect, the rest should not be affected.

+4
source share
7 answers
 $result = mysql_query($sql); if(mysql_error()) { echo "Error: " . mysql_error(); } 
+5
source

From the point of view of your original question - you cannot. The purpose of die and exit is to complete the processing of the script. If you do not want to complete script processing, do not call die or exit .

In terms of suppressing error output, this is possible using the error management operator ( @ ), but in the recommendations. (You must check the error status yourself if you suppress errors in this way.)

For example, you can use:

 $result = @mysql_query($sql); if(is_resource($result)) { // The query worked... } else { // Handle error state, perhaps using mysql_error } 

However, to make this clear, NEVER accidentally add an error suppressor to a function call. You MUST ensure that you handle any potential errors correctly.

+5
source
 $result = mysql_query($sql) or print("error with responses"); 

Echo cannot be used in logical comparisons, such as what you are trying to do. Instead, you should use print that will not cause PHP errors.

+2
source

Check mysql_query return type

 $result = mysql_query($sql); if ($result===false) { echo 'The Query failed'; } //> Continue 
+1
source

You do not need to use die as the second function call, it is just used as a convention in almost every mysql_query tutorial.

All we do is evaluate a logical expression. $result = $a OR $b . If the value of $a true, we never execute $b , because we do not need it. We performed a logical OR on one side of the statement, which is true, and that’s all we need.

The die () function immediately exits the script with the message. You can replace it with your own function to print a pretty error message and continue using the script without exiting. For instance,

 function my_error_function($status) { echo "ERROR: $status"; } $result = mysql_query($sql) or my_error_function("Uhoh. There was a problem executing $sql."); 
+1
source

You can disable the error report that you want to make in the production environment.

 error_reporting(0); 

It still throws an error, but will no longer be displayed.

It is very unusual. I can’t think of a reason to accept the mySQL error - if the problem was broken by SQL, you usually go ahead of time.

0
source

You should look for try / catch not die () or exit

0
source

All Articles