What are the best practices for iterating through query results and storing them in arrays when working with MySQL tables in PHP?

When iterating through query results in PHP and storing them in arrays, it is important to use a loop to fetch each row from the result set and store it in an array. This can be achieved by using functions like mysqli_fetch_assoc() or mysqli_fetch_array(). It is also recommended to check if the result set is not empty before attempting to iterate through it.

// Assuming $conn is the mysqli connection object and $query is the SQL query
$result = mysqli_query($conn, $query);

if(mysqli_num_rows($result) > 0) {
    $data = array();

    while($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }

    // Now $data array contains all the rows from the query result
} else {
    echo "No results found.";
}