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>
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!