How can SQL query results be stored in variables and used globally in PHP?

To store SQL query results in variables and use them globally in PHP, you can fetch the results into an array and then assign it to a global variable. This allows you to access the query results throughout your PHP script without having to run the query multiple times.

// Connect to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');

// Check connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Run SQL query
$sql = "SELECT * FROM table";
$result = $connection->query($sql);

// Fetch results into an array
$data = array();
while ($row = $result->fetch_assoc()) {
    $data[] = $row;
}

// Assign the data array to a global variable
$GLOBALS['query_results'] = $data;

// Now you can access $query_results globally in your PHP script
foreach ($GLOBALS['query_results'] as $row) {
    echo $row['column_name'] . "<br>";
}

// Close the connection
$connection->close();