uchi February 2016

set mysql connect to a php and access them from multiple php functions

I have a php file, which connects to a mysql database using:

  $mysqli = mysqli_connect("localhost","user","pass","db");

And on the same php, there are some functions that made use of that connection, and make querys...

I dont know how to set $mysqli to the entire php and call to it from functions, instead of repeating the connection on every function...

(I have 3 functions, i need to repeat the code of connection on every function, making at the end, 3 connections to the same database. I want to avoid that, and make one connection, and use it on the 3 functions without making another connection more.

Is there any way?

thanks

Answers


AbraCadaver February 2016

There's got to be dupes, but here's two ways:

Pass it into the function:

$mysqli = mysqli_connect("localhost","user","pass","db");
$something = test($mysqli);

function test($conn) {
    mysqli_query($conn, 'stuff);
}

Or access the global variable:

function test() {
    mysqli_query($GLOBALS['mysqli'], 'stuff');
}


Adam Hull February 2016

You need to have your function look like

 function something(){
    global $mysqli;
    // Rest of function
    }

This is just one way you can do this


BryanT February 2016

You can have a separate php module that "wraps" your mysqli calls.

function Sql_Query($query) {

$result = mysqli_query($database_connection, $query);
if (Sql_Check_Error($database_connection))
   dbg("Sql error in $query"); // Some debugging code
}
return $result;

}

Where Sql_Error_Check is yet another "wrapped" mysqli call, etc...

And this is a global.

$database_connection = Sql_Connect($database_host,$database_user,$database_password,$database_name);

There's an even better Object Oriented for mysqli. http://php.net/manual/en/mysqli.quickstart.dual-interface.php

Post Status

Asked in February 2016
Viewed 3,110 times
Voted 5
Answered 3 times

Search




Leave an answer