Home  >  Article  >  Database  >  How to Echo Table Rows from a MySQL Database in PHP?

How to Echo Table Rows from a MySQL Database in PHP?

DDD
DDDOriginal
2024-11-01 21:37:02251browse

How to Echo Table Rows from a MySQL Database in PHP?

Echoing Table Rows from a Database (PHP)

In the realm of PHP programming, it's often necessary to extract data from MySQL databases and display it as part of dynamic web applications. To do this effectively, understanding how to echo out table rows from the database is crucial.

In this programming scenario, a user aims to display all the rows from a specific table. While accessing individual rows using methods like mysql_result is limited to retrieving one row at a time, the goal is to iterate through and echo out the entire result set.

The solution lies in utilizing the mysqli_query() and mysqli_fetch_assoc() functions. Let's break down the provided code:

<code class="php">$sql = "SELECT * FROM MY_TABLE";
$result = mysqli_query($conn, $sql); // First parameter is the return of "mysqli_connect()" function</code>

Here, a MySQL query string is constructed using $sql. The mysqli_query() function executes the query against the database connection established through $conn and returns a result object stored in $result.

<code class="php">echo "<br>";
echo "<table border='1'>";</code>

Before displaying the table, a line break and a table with borders are added to enhance readability.

<code class="php">while ($row = mysqli_fetch_assoc($result)) { // Important line, returns assoc array
    echo "<tr>";
    foreach ($row as $field => $value) { 
        echo "<td>" . htmlspecialchars($value) . "</td>"; 
    }
    echo "</tr>";
}</code>

The key to iterating through table rows lies in the mysqli_fetch_assoc() function. It retrieves the next row from $result as an associative array, where column names are mapped to their values. Using a foreach loop, we can iterate over each column in the row and echo its value within a table data (TD) element.

Finally, the table is closed, completing the display of all table rows from the database query. By employing this approach, developers can effortlessly echo out and display table data in their PHP applications.

The above is the detailed content of How to Echo Table Rows from a MySQL Database in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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