Continue after or die in Php
I am currently working on a PHP project with MySQL. I have the PHP tag at the top and bottom of the page to start and end the PHP. In between the PHP tags I am opening an echo statement output HTML to the browser. In parts of the page where I need to perform PHP, I end the echo tag and perform a MySQL Query using
mysql_query($myQuery) or die("Error");
When the MySQL has开发者_高级运维 an error, it stops at that point and the rest of the HTML isn't shown which obviously affects the design of the page.
How can I get the HTML part to continue if the MySQL fails to run.
An example of your code would be useful, but in general, the mysql_query() or die()
pattern is not necessary. If you don't want execution to halt upon the failure of a given query, simply omit the or die()
part:
echo 'Output something';
$res = mysql_query($sql);
if ($res) {
/* do stuff with the query results */
} else {
/* output an error if desired... or don't */
echo 'There was a database error: '.mysql_error();
}
echo 'Output some more stuff';
Just replace the die() with some other command. See this article
So use print
instead of die
?
You put the result of the mysql_query function in a variable and test that.
<?php
$result = mysql_query($query);
if ($result) then { echo "query was a success"; }
else { echo "query failed"; }
//rest of the program continues here...
echo "on with the show";
Using die
will cause the server to stop processing the remaining page. If you want to display an error and continue loading the page, use:
... mysql_query($myQuery) or echo "Error";
using 'or die()' is just a quick way of handling errors that really shouldn't happen.
One way that could be better is instead of using echo, put all the output in a variable. when you run anything that could error out, wrap it in an if
statement (or try
/ catch
block), and either handle the error gracefully on the same page, or include()
an error page and exit
.
I feel that using die()
in a production app is really not acceptable.
精彩评论