How can a while loop be used to properly fetch and store multiple rows from a MySQL query in PHP?
When fetching and storing multiple rows from a MySQL query in PHP, a while loop can be used to iterate through each row returned by the query and store them in an array or process them individually. Inside the while loop, the fetch_assoc() method can be used to fetch each row as an associative array, which can then be stored or processed as needed.
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Query to fetch multiple rows
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);
// Initialize an empty array to store the fetched rows
$rows = array();
// Use a while loop to fetch and store each row
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row; // Store each row in the array
}
// Close the database connection
mysqli_close($connection);
// Process the fetched rows as needed
foreach ($rows as $row) {
// Process each row here
}
Keywords
Related Questions
- How can the functionality of navigating through data sets be optimized in PHP for better performance?
- What are potential optimization strategies for a PHP script that reads a large CSV file and compares data with a MySQL table?
- Can you provide an example of using the "!" operator with in_array in PHP for checking prohibited file extensions in an upload script?