PHP Database Connection OOP


..\school\DbCon.php
<?php
class DbCon {
private $db = null;
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=db_utility', 'root', '');
}

public function SqlSelect() {
$Sql = "SELECT * FROM users";
$stmt = $this->db->query($Sql);
$stmt->execute();
$data = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
return $data;
}
}
?>

..\school\result.php
<?php 
require_once 'DbCon.php';
$obj= new DbCon();
print '<pre>';
$result =$obj->SqlSelect();
foreach ($result as $key => $value) {
print_r($value['id']);
print_r($value['username']);
print_r($value['fname']);
print_r($value['lname']);
echo '<hr/>';
}
?>
Output:



Your Can Also Use:

PDO::FETCH_NUM
PDO::FETCH_BOTH

PDO::FETCH_OBJ
Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment