Question:
Continue Parse PHP after DB Connection Error?
clievers
2006-04-24 20:09:01 UTC
Hi there, I'm working on a piece of my website that reads info from the database, and displays it. It works great. So now I want to see what happens when a database connection error occurs, so I stop the mysql service. What happens, is a message is printed to the screen saying it can't connect (auto mysql message), but my entire php script stops parsing.

How can I get it to keep going, just not display the database results?

Thanks.
Three answers:
Don T
2006-04-24 20:36:07 UTC
Capture and test the return value from mysql_connect(). If it's not FALSE, it contains your DB resource. If it FALSE, do some other processing. e.g.



if( mysql_connect( whatever ) )

{

do something;

}

else

{

do something else;

}



// or more commonly:



if( ! mysql_connect( whatever ) )

{

do error processing;

}

else

{

do normal processing;

}



Note that you should disable error displays on production servers in your php.ini file. (Errors will still appear in you apache error log.) e.g.

#php.ini

...

display_errors = Off



Alternatively, you can use this function from your code:



error_reporting(0);
vikram
2006-04-25 00:16:41 UTC
Basically, you need to test if the connection was successful or not, would be good to use a class to handle the connections, and also check even after the connection is made, if you dont get the required results then put checks on it. For your question hope the following helps:




$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');

if ($link)

{

echo 'Connected successfully';

// all the code which gets the results from the database.

mysql_close($link);

}



// all the rest of the code on your website which does not require the database connection.

?>
duncan_311
2006-04-24 20:36:16 UTC
I write in .net and we use a try-catch block. I don't know if PHP has something similar, but you might search for "catching exceptions" and see what you get.

Good luck.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...