Jake Snake
Jake Snake

Reputation: 165

How to make mysqli connect function?

I'm having a problem with a function that connects me to the database using mysqli. What I'm aiming to have is to just type getConnected(); where I need the connection.

This is the code:

function getConnected()
{
    $host = 'localhost';
    $user = 'logintest';
    $pass = 'logintest';
    $db = 'vibo';

    $mysqli = new mysqli($host, $user, $pass, $db);

    if ($mysqli->connect_error) {
        die('Connect Error (' . mysqli_connect_errno() . ') '
            . mysqli_connect_error());
    }
}

This is the error I get when I try to use $mysqli after calling getConnected():

Notice: Undefined variable: mysqli in C:\xampp\htdocs\xampp\loginsystem\index.php on line 19

Upvotes: 7

Views: 29943

Answers (2)

Dharman
Dharman

Reputation: 33413

You don't need to create such function. The connection to mysqli is only 3 lines of code when done properly. Definition and execution of such function would add twice as much.

Remember to always follow the three steps when opening a connection:

  1. Enable mysqli error reporting.
  2. Create instance of mysqli class.
  3. Set the proper charset. Recommended one is utf8mb4

If you would like to have these 3 lines wrapped in a function you could do something like this:

function getConnected(): \mysqli {
    $host = 'localhost';
    $user = 'logintest';
    $pass = 'logintest';
    $db = 'vibo';

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $mysqli = new mysqli($host, $user, $pass, $db);
    $mysqli->set_charset('utf8mb4');

    // return the instance of mysqli class
    return $mysqli;
}

However, hardcoding the values does not make much sense. The values should be coming either from environment variables (e.g. read using getenv() function) or from config file. For example:

function getConnected(): \mysqli {
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $mysqli = new mysqli(getenv('DB_HOST'), getenv('DB_USER'), getenv('DB_PASS'), getenv('DB_NAME'));
    $mysqli->set_charset('utf8mb4');

    // return the instance of mysqli class
    return $mysqli;
}

Upvotes: 1

Sam
Sam

Reputation: 2970

As some users have suggested (and is the best way), return the mysqli instance

function getConnected($host,$user,$pass,$db) {

   $mysqli = new mysqli($host, $user, $pass, $db);

   if($mysqli->connect_error) 
     die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

   return $mysqli;
}

Example:

$mysqli = getConnected('localhost','user','password','database');

Upvotes: 13

Related Questions