0

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

0

3 Answers 3

2

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');
}
Sign up to request clarification or add additional context in comments.

Comments

1

You need to have your function look like

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

This is just one way you can do this

Comments

-1

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

2 Comments

that calls the function on every query, that is even worst, you connect every time you do a query
My own code was actually very much like @AbraCadaver's - I over simplified it here to avoid having to explain where the GLOBAL was.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.