Page 1 of 1
MySQL connection - error handling
Posted: Tue Dec 15, 2009 2:21 am
by reiver
When the connection to a MySQL database fails, I just wondered if there's a recommended error handling method?
All I can find trying to research this is the ubiquitous
Code: Select all
mysql_connect($hostname,$username,$password) OR die ("could not connect");
or variation of it.
What I'd like is a) a sensible message to the user and b) an email alert sent to the administrator. I think I can devise a clunky way to do this but can't help thinking there might be an elegant way to achieve it...
...but I'm afraid my PHP coding and the word 'elegant' don't sit easily together...;-(
John
Re: MySQL connection - error handling
Posted: Tue Dec 15, 2009 10:40 am
by kalthar
You could always try throwing exceptions
http://php.net/manual/en/language.exceptions.php
It has a bunch of in-built functions for making error reporting pretty
Re: MySQL connection - error handling
Posted: Wed Dec 16, 2009 1:42 am
by reiver
Thanks for that and I'll look into it.
On first glance, though, it seems to come up against the same issue that I was originally trying to figure a way around. If the connection to the database fails then I want to send an email alert to the admin. I only want to do this once, though, as there's no point sending one every time it fails - this would be a real pain on a busy site.
I suppose my emphasis is on finding a simple way - perhaps 'elegant' isn't the right word - to send just a single alert.
John
Re: MySQL connection - error handling
Posted: Wed Dec 16, 2009 2:36 am
by Eran
The common practice, instead of using die() (which should never happen on a production machine), is to log the error and show the appropriate error page.
mysql_connect() returns false on error, so just check the results instead of die()ing -
Code: Select all
$connection = mysql_connect(...);
if($connection === false) {
$error = mysql_error(); //Get the error message
mail('admin@mysite.com','Database error',$error); //Mail yourself the error
}
You can wrap this in a function or invoke it in a class, it doesn't matter. If you want the Email to be sent only once, set a flag in a local file and read it before sending the Email. Reset it manually after you've resolved the database issue.
Re: MySQL connection - error handling
Posted: Wed Dec 16, 2009 7:51 am
by reiver
Yep, I think I'd decided that writing a flag to a local text file was the way to go so thanks for confirming that approach. A tad clunky maybe but I guess it'll do the job.
I hadn't appreciated that - from what you say - the use of the ubiquitous die() seems a bit of a no-no. Still, that's good to hear as it makes for a much more flexible response.
Anyway, thanks again - most helpful!
John