How can SQL query results be properly stored and passed as session variables in PHP for use in subsequent pages?

To store SQL query results as session variables in PHP for use in subsequent pages, you can fetch the data from the database, store it in an array, and then assign the array to a session variable. This way, the data will persist across different pages as long as the session is active.

<?php
// Start the session
session_start();

// Make a database connection
$connection = mysqli_connect("localhost", "username", "password", "database");

// Fetch data from the database
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);

// Store the data in a session variable
$_SESSION['query_results'] = $data;

// Close the database connection
mysqli_close($connection);
?>