Iterating Through MySQL Result Sets
Traversing a result set retrieved from a MySQL database is a fundamental task in PHP programming. For beginners in this domain, grasping the various methods of looping through these sets can be invaluable.
One straightforward approach is demonstrated in the code snippet below:
$link = mysql_connect(/*arguments here*/); $query = sprintf("select * from table"); $result = mysql_query($query, $link); if ($result) { while($row = mysql_fetch_array($result)) { // Perform actions on the row } } else { echo mysql_error(); }
In this code, we first establish a connection to the database ($link**). Subsequently, we execute a query, capturing the result in the **$result variable. The code then enters a loop, using mysql_fetch_array() to retrieve each row from the result set as an associative array ($row), allowing you to access individual column values. Actions can then be performed on each row until the entire result set is exhausted.
The above is the detailed content of How Do I Iterate Through MySQL Result Sets in PHP?. For more information, please follow other related articles on the PHP Chinese website!