What is the best practice for storing the output of a MySQL query in PHP as a variable instead of directly echoing it?

When storing the output of a MySQL query in PHP as a variable instead of directly echoing it, it is best practice to fetch the result from the query using a fetch method (such as fetch_assoc, fetch_row, fetch_array) and assign it to a variable. This allows you to manipulate or use the data further in your PHP code before displaying it.

// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Run a query
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

// Fetch and store the result in a variable
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $data[] = $row;
    }
}

// Close connection
mysqli_close($connection);

// Now you can use the $data variable for further processing or displaying the data