Wednesday, February 7, 2018

Using PHP Data Objects (PDO) for Reading Data

<?php
try{
    $pdo = new PDO("mysql:host=localhost;dbname=demo", "root", "");
    $sql = "SELECT * FROM persons"; 
    $result = $pdo->query($sql);
    if($result->rowCount() > 0){
        echo "<table border='1' align='center' width='50%'>";
            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()){
            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
        unset($result);
    } else{
        echo "No records matching your query were found.";
    }
} catch(PDOException $e){
    die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}

// Close connection
unset($pdo);
?>

No comments:

Post a Comment