RE: [PHP] php die function for MySQL connection errors
| From: | Ford, Mike [LSS] | Date: | Sat, 14 Aug 2004 14:37:53 +0000 |
| Subject: | RE: [PHP] php die function for MySQL connection errors | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-193798@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: John Gostick
> Sent: 14/08/04 15:19
> I have a quick question about using the PHP die() function.
[...]
> I changed the code to this:
>
> $connection = mysql_connect($host, $user, $password)
> or die("Error connecting to SQL server");
> $db = mysql_select_db($database, $connection)
> or header('Location: ../errors/databaseselect.php');
>
> Which works fine (tested by deliberately misnaming database so it can't
find it).
>
> However if I then use the same approach for the server connection error,
> like below, it doesn't work.
>
>
> $connection = mysql_connect($host, $user, $password)
> or header('Location: ../errors/servererror.php');
On failure, this causes the header to be sent, but doesn't actually stop execution of your
script, so...
> $db = mysql_select_db($database, $connection)
this will now fail because you don't have a valid $connection.
> or header('Location: ../errors/databaseselect.php');
The bottom line is, whenever you issue a header("Location: ....") call, you also need to
cause the script to die if your logic demands that -- so the above should be written something like:
if (!$connection = mysql_connect($host, $user, $password)):
header('Location: ../errors/servererror.php');
die();
endif;
if (!$db = mysql_select_db($database, $connection)):
header('Location: ../errors/databaseselect.php');
die();
endif;
(And, BTW, the HTTP definition says that the Location: header should specify a full absolute URL, so
that should be:
header("Location: http://your.server.name/path/to/errors/servererror.php");
etc.)
Cheers!
Mike