Home > Database > Mysql Tutorial > How to Display Database Table Rows as HTML in PHP?

How to Display Database Table Rows as HTML in PHP?

Linda Hamilton
Release: 2024-11-02 03:20:02
Original
559 people have browsed it

How to Display Database Table Rows as HTML in PHP?

How to Display Database Table Rows as HTML

In PHP, retrieving data from a database is a common task. However, when you wish to display multiple table rows, you might face challenges.

To resolve this issue, you can use the following steps:

  1. Establish Database Connection:
    Establish a connection to your MySQL database using mysqli_connect().
  2. Execute Query:
    Execute your SQL query to retrieve the table rows using mysqli_query().
  3. Fetch Associative Array:
    Use mysqli_fetch_assoc() to fetch the query results as an associative array. This will store each row as an array, with column names as keys and values as array elements.
  4. Iterate Rows:
    Utilize a while loop to iterate through the rows.
  5. Create HTML Table:
    Start by echoing an HTML table heading with the desired border.
  6. Echo Row Data:
    Within the while loop, iterate through each row and echo the column values within HTML table data cells
  7. .
  8. Close HTML Table:
    Once all rows have been echoed, close the HTML table.
  9. Here is an example code that demonstrates these steps:

    <code class="php">$sql = "SELECT * FROM MY_TABLE";
    $result = mysqli_query($conn, $sql);
    
    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

    This code will generate an HTML table with all the rows from the database table.

    The above is the detailed content of How to Display Database Table Rows as HTML 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