Pages

PHP OOP PDO Database class example

Read / fetch data with PHP PDO Database Connection Class in Simple way

<?php
class db {
    private $username = "root";
    private $password = "";
    function connect() {
        $username = $this->username;
        $password = $this->password;
        try {
            $conn = new PDO('mysql:host=localhost;dbname=test', $username, $password);
        } catch (Exception $ex) {
            die($ex->getMessage());
        }
        return $conn;
    }
}

class getdata extends db {
    function read() {
        $con = $this->connect();
        $sql = "SELECT * FROM CITY";
        try {
            $citylist = $con->query($sql);
        } catch (Exception $ex) {
        }
        return $citylist;
    }
}

$getdataCity = new getdata();
$citylist = $getdataCity->read();

$a = $citylist->fetchAll();

print_r($a);

if($citylist->rowCount()){
    foreach ($a as $city){
        echo $city['city_name'];
    }
}

No comments:

Post a Comment

Search This Blog