mysqli连接错误后无法重定向

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

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

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

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