Home >Database >Mysql Tutorial >How to Echo Table Rows from a Database Using PHP?

How to Echo Table Rows from a Database Using PHP?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 06:13:02810browse

How to Echo Table Rows from a Database Using PHP?

Echoing Table Rows from a Database using PHP

Echoing individual rows from a database query can be achieved using PHP's mysqli functions. Let's explore how to accomplish this:

Start by establishing a connection to your database using mysqli_connect(). Execute your query using mysqli_query(). To fetch rows from the result, use mysqli_fetch_assoc(), which returns an associative array for each row.

Inside a loop, iterate through the rows and columns. For each column, echo the value using htmlspecialchars() to prevent malicious code execution.

Here's an example code:

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

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>

This code will generate a table filled with the data from your database. Each row will be represented as a table row, and each column value will be enclosed within a table cell.

The above is the detailed content of How to Echo Table Rows from a Database Using 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