I have recently adjusted the way I make create my mysqli
connections. Initially I would include
the connection file and use if($mysqli->connect_error)...
in my main script. Now I check if there is an issue with the connection within the connection file. If there isnt an issue then I just check that the variable name for the connection is set. Before I continue Im curious if there are any issues with the way I am doing this and if it goes against any 'best-practices'. See edit 2 for reasoning
The contents of my connection file: (connect_db_login.php)
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try{
$test = new mysqli('localhost:3306','login','password','testdb');
$test->set_charset('utf8');
}catch(Exception $e){ //$e not used; dead code?
echo('<script> alert("Connection to database failed!");</script>');
header("refresh:0; url=../login.php"); //using refresh because location doesnt wait for script
}
Checking that the connection has been made in main script:
<?php
include('../connect_db_login.php'); // using include not require
if(isset($test)){
...
edit
I could also check the connection with
<?php
include('../connect_db_login.php'); // using include not require
if(isset($test)===false){
exit()
}else{
...
edit 2
I opted to attempt this because mysqli_report()
would prevent the if
in the following code:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$test = new mysqli('localhost:3306','login','password','test');
$test->set_charset('utf8');
if($test->connect_error)
die('Connection failed');