views:

39

answers:

2

Hey everyone!
I'm building a webapp in PHP that uses a MySql DB. What I want to do is for example when someone tries to access to a page, but the DB throws an error, to display a HTML (or redirect) page with the HTTP code 500. Something like the "fail whale" in Twitter. Is that possible?

+2  A: 

You could use the die function in PHP to do this like so.

mysql_connect("details go here")or die(require("failed.php"));

That will attempt to connect to your database and if it fails will require another file, you could also create a function that redirects users and stick that inside the die() function and simply redirect them to another page, either way that's how you would send users away upon an error with the connection.

Tom Walters
But If I do this, and the failed.php has the `header("Location /path/to/anything"); ` it outputs "Cannot modify header information - headers already sent"
Francesc
Well you could redirect using JavaScript or a meta tag instead, so put a function name inside the brackets and then do the following - function redirect(){ echo '<meta http-equiv="refresh" content="0;url=http://example.com/failed.php">' }
Tom Walters
at first output php generates headers and sends them to the client. if ou make any output and afterwards try to do a header() then you will get the error you just got
ITroubs
A: 

If there is an error in mysql it will return FALSE instead of a resource. You can then do the following to test and conditionally redirect:

// This also works for mysql_connect( ... ); and all other <dbtype>_<command> 
// functions, including MySQLi, Oracle, and PSQL extensions.
$cond = mysql_query( $resource, $query );
if( $cond === FALSE )
{
    // You can replace this with any other error handling you'd like.
    header( "Location: url/of/error/page" );
    die();
}
Christopher W. Allen-Poole
SELECT * FROM pages WHERE name='Bunny' won't be an error as far as i know and so will return true. i think OP want's to know how to redirect if there are no matching lines in his database
ITroubs
@ITroubs If he has another condition where the DB isn't throwing an error (and that is the OP's question), then he can replace <code>$cond === FALSE</code> with something like <code>mysql_count_rows( $cond ) == 0</code>. But, that is not the question he asked.
Christopher W. Allen-Poole
indeed the formulation of his question is a bit misleeding
ITroubs