Show Values From A MySQL Database Table Inside A HTML Table On A Webpage

To display values from a MySQL database table inside an HTML table on a webpage using PHP, you can use the following code:

<?php

// Connect to the MySQL database
$host = 'localhost';
$db = 'your_database_name';
$user = 'your_username';
$pass = 'your_password';

$conn = new mysqli($host, $user, $pass, $db);
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error);
}

// Fetch data from the table
$sql = 'SELECT * FROM your_table_name';
$result = $conn->query($sql);

?>

<!DOCTYPE html>
<html>
<head>
    <title>MySQL Database Table</title>
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
        }
        th, td {
            padding: 8px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
    </style>
</head>
<body>

<h2>MySQL Database Table</h2>

<table>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
    </tr>
    <?php while($row = $result->fetch_assoc()): ?>
    <tr>
        <td><?php echo $row['id']; ?></td>
        <td><?php echo $row['name']; ?></td>
        <td><?php echo $row['email']; ?></td>
    </tr>
    <?php endwhile; ?>
</table>

<?php
// Close the database connection
$conn->close();
?>

</body>
</html>

Make sure to replace the following placeholders in the code with your MySQL database details:

  • your_database_name with the name of your database.
  • your_username with your MySQL username.
  • your_password with your MySQL password.
  • your_table_name with the name of the table you want to display.

This code will connect to the MySQL database, fetch the data from the specified table, and display it in an HTML table on the webpage.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!