How can global variables be used in PHP functions to maintain database connections without causing issues?
Global variables can be used in PHP functions to maintain database connections by declaring the database connection as a global variable outside of the function and then referencing it within the function using the `global` keyword. This ensures that the database connection remains open throughout the execution of the script without having to constantly reconnect to the database within each function call.
<?php
$connection = null;
function connect_to_database() {
global $connection;
$connection = mysqli_connect('localhost', 'username', 'password', 'database');
if (!$connection) {
die('Could not connect to database: ' . mysqli_connect_error());
}
}
function query_database($query) {
global $connection;
if ($connection === null) {
connect_to_database();
}
$result = mysqli_query($connection, $query);
if (!$result) {
die('Error executing query: ' . mysqli_error($connection));
}
return $result;
}
// Example usage
$query = "SELECT * FROM users";
$result = query_database($query);
while ($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . '<br>';
}
mysqli_close($connection);
?>