0

I am new to php. I am trying to redirect to a error page in php when I get a mysql connection error, but I get an error stating that I cannot modify the header because the output was already sent on line 8 (where I created the connection). Please can you advise on the proper way of doing this?

<?php
$servername = "localhost:3306";
$username = "danny";
$password = "sql1";
$dbname = "testdb";

  try{
      $conn = new mysqli($servername, $username, $password, $dbname);
  }
  catch(Exception $e){
  header('Location: /connection_error.php');
  die();
}


?>

Thanks

Danny

DannyR
  • 69
  • 8

3 Answers3

3

You need to add this line at the top to tell mysqli to throw exceptions

mysqli_report(MYSQLI_REPORT_STRICT); 
$servername = "localhost:3306";
$username = "danny";
$password = "sql1";
$dbname = "testdb";

  try{
      $conn = new mysqli($servername, $username, $password, $dbname);
  }
  catch(Exception $e){
  header('Location: /connection_error.php');
  die();
}
Agam Banga
  • 2,708
  • 1
  • 11
  • 18
0

Additionally, you can always check the error code from the last connect call by using mysqli::$connect_errno, whereas it returns an error code value for the last call, if it failed. Zero means no error occurred (hence the falsey).

<?php
    /* Variable Defaults */
    $servername = 'localhost:3306';
    $username   = 'danny';
    $password   = 'sql1';
    $dbname     = 'testdb';

    /* Make Connection */
    $conn = new mysqli($servername, $username, $password, $dbname);

    /* Check Connection */
    if($conn->connect_errno) {
        /* Redirect */
        header('Location: /connection_error.php');
        exit();
    }
?>
Daerik
  • 4,167
  • 2
  • 20
  • 33
  • If your `mysqli` call is displaying a notice, you will not be able to use `header()` since the headers have already been sent. I would suggest modifying your `error_reporting` to not display notices. – Daerik May 01 '17 at 17:04
-1

Try this

<?php
ob_start();

$servername = "localhost:3306";
$username = "danny";
$password = "sql1";
$dbname = "testdb";

  try{
      $conn = new mysqli($servername, $username, $password, $dbname);
  }
  catch(Exception $e){
  header('Location: /connection_error.php');
}

ob_flush();
?>
Mhd.Jarkas
  • 406
  • 2
  • 5
  • 11