1

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');
FamousAv8er
  • 2,345
  • 2
  • 9
  • 27
  • Here is the full manual on MySQL in PHP https://www.php.net/manual/en/book.mysqli.php , it will help you a lot. Lots of examples there. – Greeso Dec 20 '19 at 21:45
  • Or do a search like : https://stackoverflow.com/search?q=mysqli+database+connection –  Dec 20 '19 at 22:10
  • 2
    That's a very good question. In short - yes, the last one indeed would make `if` superfluous. Please read my article on [PHP error handling](https://phpdelusions.net/articles/error_reporting) for the details. Basically you should (almost) never handle mysqli errors specifically but rather configure your PHP at whole to handle all kinds of error uniformly. – Your Common Sense Dec 20 '19 at 22:59
  • 2
    @Greeso unfortunately, *none* of these examples are *any* good. – Your Common Sense Dec 20 '19 at 23:00
  • 1
    Instead of `include` use `require` and your `isset` becomes also superfluous. – Dharman Dec 21 '19 at 00:37

0 Answers0