uchi
uchi

Reputation: 101

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

Upvotes: 0

Views: 143

Answers (3)

BryanT
BryanT

Reputation: 412

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

Upvotes: -1

Adam Hull
Adam Hull

Reputation: 194

You need to have your function look like

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

This is just one way you can do this

Upvotes: 1

AbraCadaver
AbraCadaver

Reputation: 78994

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');
}

Upvotes: 2

Related Questions