How do I allow a function to access a database connection without using GLOBAL?
config.php
DEFINE (\'DB_HOSTNAME\', \'hostname\');
DEFINE (\'DB_DAT
Either pass the database handle to your function, as @KingCrunch and others have said, or call a function that returns the handle:
In config.php
:
function get_dbc() {
$dbc = mysqli_connect(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(!$dbc) die("Unable to connect to MySQL: " . mysqli_error($dbc));
return $dbc;
}
In functions.php
:
require_once('config.php');
function something()
{
$dbc = get_dbc();
$info = mysqli_query($dbc, "SELECT info FROM text") or die("Error: ".mysqli_error($dbc));
}
You may wish to look at The mysqli Extension and Persistent Connections for details on how you can prevent the connection from being re-established on each call to get_dbc()
. There are alternative approaches to this, such as creating a singleton class for your database connection.