I have a helper file that contains quite a few functions, but no "main" function. Each of these helper functions requires a database connection. To improve code maintainability, I'd like to put the variable that holds the database connection in a global state (outside of any of the functions) such that each function has visibility to it and can use it in their mysql calls. Here is what I mean:
$path = $_SERVER['DOCUMENT_ROOT'];
$connection = $path . '/scripts/connection.php';
include ($connection); // this initializes the variable '$link'
function getLocation ($id) {
$sql = "SELECT name FROM Locations WHERE id=$id";
$result = mysqli_query($link, $sql);
if (!$result) { return -1; }
$row = mysqli_fetch_array($result);
mysqli_close($link);
return $row['name'];
}
function getGroupID($group_id) {
$sql = "SELECT id FROM Groups WHERE group='$group_id'";
$result = mysqli_query($link, $sql);
if (!$result) { return -1; }
$row = mysqli_fetch_array($result);
mysqli_close($link);
return $row['id'];
}
// and many other similar functions
I'd rather not put those three global lines inside of each function since then I have to repeat code over and over, but this method has no global scope. I could probably look into passing the $link
variable in as an argument, but that would require refactoring a LOT of function calls. I know that some frown on global variables like this, but in this case it is my simplest resolution.
As an aside, if I replace the three global lines with this:
include '../scripts/connection.php'
my code works fine, but then I lose some of the relative referencing flexibility. I don't understand why the code that I post here operates differently.
Is there a way that I can declare this $connection
variable globally?
Thank you.