treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Redirect users if there is a database connection error.

  • 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.

    error_reporting(0);
    
    $myconnection = mysql_connect("localhost","root","") or die($myconnection);
    $dbconnection = mysql_select_db("db") or die($dbconnection);
    
    if (die($myconnection) === true){
      header("Location: redirect.html");
    }
    
  • 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.

    error_reporting(0);
    
    $myconnection = mysql_connect("localhost","root","") or redirect();
    $dbconnection = mysql_select_db("db") or redirect();
    
    function redirect (){
      header("Location: redirect.html");
      exit();
    }
    
  • 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 :)