Home > Database > Mysql Tutorial > body text

How to Display All Rows from a Database Query in PHP?

Barbara Streisand
Release: 2024-11-03 03:17:28
Original
831 people have browsed it

How to Display All Rows from a Database Query in PHP?

Fetching and Displaying Database Table Rows in PHP

In this question, the user expresses their desire to echo out all the rows returned by a particular query in a database. Initially, they encountered limitations as they could only retrieve one row at a time.

To address this issue, we can utilize the mysqli_fetch_assoc() function, which returns an associative array for each row in the result set. Here's how it can be implemented:

<code class="php">$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql);

echo "<br>";
echo "<table border='1'>";

while ($row = mysqli_fetch_assoc($result)) { 
    echo "<tr>";
    foreach ($row as $field => $value) { 
        echo "<td>" . htmlspecialchars($value) . "</td>"; 
    }
    echo "</tr>";
}
echo "</table>";</code>
Copy after login

In this script, we first query the database using the mysqli_query() function and store the result in the $result variable. Then, we use a while loop to iterate through the result set and fetch each row as an associative array using mysqli_fetch_assoc().

Within the loop, we build an HTML table row for each row in the result set, using the data from the associative array. We use htmlspecialchars() to prevent potential XSS attacks. Finally, we close the table after the loop has processed all the rows.

By utilizing this technique, we can echo out all the rows from the database query in a structured table format, allowing the user to view all the data they need.

The above is the detailed content of How to Display All Rows from a Database Query 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