Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 353
Jake Snake Avatar asked Mar 05 '13 14:03

Jake Snake


People also ask

Why is MySQLi connect () used?

The connect() / mysqli_connect() function opens a new connection to the MySQL server.

What does the mysqli_query () function do?

The query() / mysqli_query() function performs a query against a database.

How many parameters are required for MySQLi connect function in PHP?

PHP provides mysqli contruct or mysqli_connect() function to open a database connection. This function takes six parameters and returns a MySQL link identifier on success or FALSE on failure.


1 Answers

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');
like image 90
Sam Avatar answered Sep 27 '22 17:09

Sam