Treehouse: Grow your CSS skills. Land your dream job.

Redirect users if there is a database connection error.

  • # February 28, 2013 at 10:33 pm

    Hi guys, I’ve been playing with my php scripts for some time now, I just need a little help on how to redirect my visitors to another page that says a much clear message that the current website has encountered some **database connection error** or is under construction maybe. I have disabled error reporting which is – error_reporting(0);

    A really simple markup will be much appreciated. Thank you.


    $myconnection = mysql_connect(“localhost”,”root”,””) or die($myconnection);
    $dbconnection = mysql_select_db(“db”) or die($dbconnection);

    if (die($myconnection) === true){
    header(“Location: redirect.html”);

    # March 1, 2013 at 4:14 am

    I’m not an expert on php but I think `die()` terminates the script, so anything after that won’t get executed.

    For example `mysql_connect()` returns false if it fails, meaning `die()` will get executed and the script terminates. Instead call a custom function in which you set the redirect header. I think you need to call `exit()` or `die()` after setting the header, but I’m not sure about that.


    $myconnection = mysql_connect(“localhost”,”root”,””) or redirect();
    $dbconnection = mysql_select_db(“db”) or redirect();

    function redirect (){
    header(“Location: redirect.html”);

    # March 1, 2013 at 4:20 am

    Just found out this is a [double-post]( which @traq already solved… I’m slow :( Read his comment, it’s more useful then mine and he uses mysqli, which I forgot to mention :)

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.