1

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 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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"
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=example.com/failed.php">' }
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
0

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();
}

3 Comments

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 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.
indeed the formulation of his question is a bit misleeding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.