So i am fairly new to PHP and have few questions. So i have a main index page that includes a header page and a functions page. In the body of the index page, I call a few functions.
In my header include, i have my DB connection which loads with the index page. In each of my functions, i was NOT calling a new db connect because I figured that the db connection in the header would stay open while my functions ran. Well even though the db connection is opened in the header, I am getting an error message (db connection failed) when calling a function that required db access.
So I added a db connection to each of my functions and it works fine. My question is, I am opening a database connect when the page loads via the header. Then im opening another connection when each function is called which could be 3-5 more db connection calls on this page.
This doesn't seem efficient to me. Is this the correct way (calling a connect inside each function) or is there a solution/best practice so that I am only opening one db connect per page regardless of the number of functions called? Again when i remove the connection from the function itself, i get a fail. My connection function looks as follows:
function wm_connectToDatabase () {
$dbhost = "xxx";
$dbuser = "xxx";
$dbpass = "xxx";
$dbname = "xxx";
$dbconnection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()){
die("Connection Failed: ". mysqli_connect_error() ."(". mysqli_connect_errno() .")");
} else {
echo "</br>Connection Success</br>";
}
return $dbconnection;
}
So my header calls this function when index loads. Then each of my functions call it again like this:
function fctn1($table){
$db = wm_connectToDatabase ();
...function stuff here...
}
function fctn2($table){
$db = wm_connectToDatabase ();
...function stuff here...
}
Initially i assumed that the header connection would suffice for all functions so long as the functions were called on a page that had a connection in the header but I found out this is not the case. My functions only work if im opening another connection inside each function as well. I am not sure why the initial connection in the header doesn't stay open to the functions in the body of my page? Thank you for any help.
Again, when i remove the db connection from the functions, the functions "fail" as if there is no db connection even though im calling the connection in the header. Thanks.