Home > Database > Mysql Tutorial > How to Iterate Through MySQL Result Sets in PHP?

How to Iterate Through MySQL Result Sets in PHP?

Susan Sarandon
Release: 2024-12-10 03:04:08
Original
422 people have browsed it

How to Iterate Through MySQL Result Sets in PHP?

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();
}

?>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template