Tuesday, February 6, 2018

Reading Database using Object Oriented Model

<?php
$cn = new mysqli("localhost", "root", "", "cbp");
if($cn === false){
    die("ERROR: Could not connect. " . $cn->connect_error);
}

$sql = "SELECT * FROM persons";
if($result = $cn->query($sql)){
    if($result->num_rows > 0){
        echo "<table>";
            echo "<tr>";
                echo "<th>id</th>";
                echo "<th>first_name</th>";
                echo "<th>last_name</th>";
                echo "<th>email</th>";
            echo "</tr>";
        while($row = $result->fetch_array()){
            echo "<tr>";
                echo "<td>" . $row['id'] . "</td>";
                echo "<td>" . $row['first_name'] . "</td>";
                echo "<td>" . $row['last_name'] . "</td>";
                echo "<td>" . $row['email'] . "</td>";
            echo "</tr>";
        }
        echo "</table>";
        // Free result set
        $result->free();
    } else{
        echo "No records matching your query were found.";
    }
} else{
    echo "ERROR: Could not able to execute $sql. " . $cn->error;
}
$cn->close();
?>

No comments:

Post a Comment