How to Loop Through a MySQL Result Set in PHP
When working with MySQL in PHP, it's common to retrieve data from a database and iterate over the results. There are several ways to achieve this, each with its own benefits and drawbacks.
Using the mysql_fetch_array() Function
One common method is to use the mysql_fetch_array() function. This function fetches a row of data from the result set and returns it as an associative array where the column names are used as array keys.
<?php // Establish a connection to the MySQL database $link = mysql_connect(/* arguments here */); // Execute a query to retrieve data from the "table" table $query = sprintf("SELECT * FROM table"); $result = mysql_query($query, $link); // Loop through the result set using mysql_fetch_array() if ($result) { while ($row = mysql_fetch_array($result)) { // Do something with the current row data (e.g., print it) print_r($row); } } else { // Handle any errors that occurred during query execution echo mysql_error(); } ?>
The above is the detailed content of How to Iterate Through MySQL Result Sets in PHP?. For more information, please follow other related articles on the PHP Chinese website!