0

My main page calls many database functions, stored in the db.php file. In each of them, I'm connecting to the MySQL database using

$connect = mysqli_connect(SERVER_NAME,SERVER_USER,SERVER_PASS,SERVER_DB);

and then after some queries, I'm closing it with

mysqli_close($connect);

No problem so far. But I want to know is there any way to make the code faster, by executing the connection just one time in the main code, at top of all DB function calls? and then closing the connection at the bottom of the main code?

In other words, How to access a variable (here $connect) which is outside of a function, without having to pass it as a parameter to that certain function?

I tried declaring $connect as global or static But none of them worked.

Arman
  • 89
  • 2
  • 11

2 Answers2

0

Try setting the connection in the function and call it when needed.


Create db.php;

function connect(){
    $conn = @mysqli_connect(SERVER_NAME,SERVER_USER,SERVER_PASS);
    mysqli_select_db($conn, SERVER_DB);
    return $conn;
}
function close_connect($conn){
    mysqli_close($conn);
}

Use:

require_once "db.php";
$conn = connect();
// excute query
close_connect($conn);
Ly Thanh Ngo
  • 394
  • 1
  • 2
  • 15
  • But the point is I wanna access $conn directly in my queries, which are inside functions. – Arman Jun 14 '18 at 22:47
0

you can do something like this

<?php

$conn=xxx;


function abc() {

global $conn->.....;
} 



$conn=null;

this is not the best way of doing it. You should look at OOP practices with singleton pattern.

Tommys
  • 121
  • 8