Fetch Data
<?php
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
// check what type of data being pass
public function bind($param, $value, $type = null){
if(is_null($type)){
switch(true){
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
?>
<?php
// Usage
require 'classes/Database.php';
$database = new Database;
$database->query('SELECT * FROM posts WHERE id = :id');
$database->bind(':id', 2);
$rows = $database->resultset();
?>
<h1>Posts</h1>
<div>
<?php foreach($rows as $row) : ?>
<div>
<h3><?php echo $row['title']; ?></h3>
<p><?php echo $row['body']; ?></p>
</div>
<?php endforeach; ?>
</div>