Google News
logo
Put the resut in an HTML table (Object-oriented) in PHP
In the following example of PHP program that retrieves data from a MySQL database using the MySQLi extension in an object-oriented way and displays the results in an HTML table :
Program :
<?php
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL query
$sql = "SELECT id, name, email FROM users";

// Execute query and get result object
$result = $conn->query($sql);

// Check if any rows are returned
if ($result->num_rows > 0) {
    // Start table markup
    echo "<table>";
    echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";

    // Loop through each row and output data in table cells
    while($row = $result->fetch_assoc()) {
        echo "<tr><td>".$row["id"]."</td><td>".$row["name"]."</td><td>".$row["email"]."</td></tr>";
    }

    // End table markup
    echo "</table>";
} else {
    echo "0 results";
}

// Close connection
$conn->close();
?>
This program connects to the MySQL database using the provided credentials, executes an SQL query to retrieve data from the "users" table, loops through each row in the result object, and outputs the data in an HTML table.

If no rows are returned, it displays "0 results". Finally, it closes the connection to the database.