class db {
private $_pdo ,
$_query,
$_error = false,
$_results ,
$_count = 0 ;
private function __construct () {
try {
$host = config::get('mysql/host');
$database = config::get('mysql/db');
$username = config::get('mysql/user');
$pasword = config::get('mysql/password');
$this->_pdo = new PDO("mysql:host=$host;dbname=$database", $username, $pasword);
} catch (PDOException $e) {
die($e->getMessage()) ;
}
}
public static function getInstance() {
if(!isset(self::$_instance)) {
self::$_instance = new db () ;
}
return self::$_instance ;
}
public function query($sql,$params=array()) {
$this->_error = false ;
if($this->_query = $this->_pdo->prepare($sql)) {
$x = 1 ;
if(count($params)) {
foreach($params as $param) {
$this->_query->bindValue($x,$param) ;
$x++ ;
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ) ;
$this->_count = $this->_query->rowCount() ;
} else {
$this->_error = true ;
}
}
return $this ;
}
public function action($action , $table ,$where = array()) {
if(count($where) === 3) {
$operators = array('=','>','<','>=','<=') ;
$field = $where[0] ;
$operator = $where[1] ;
$value = $where[2] ;
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {field} {operator} ?" ;
if(!$this->query($sql,array($value))->error()) {
return $this ;
}
}
}
return false ;
}
public function get($table , $where) {
return $this->action("SELECT *",$table,$where) ;
}
public function delete($tabale , $where) {
return $this->action('DELETE' ,$table , $where) ;
}
public function count() {
return $this->_count ;
}
public function error() {
return $this->_error ;
}
}
index.php
$a = db::getInstance()->get('users',array('username','=','ram')) ;
if(!$a->count()) {
echo "No User" ;
} else {
echo "OK " ;
}
There is an error on index file:
Fatal error: Call to a member function count() on Boolean in line 4.
Your ->get(..)
method returns the value from ->action
which is a boolean
so do it so:
$a = db::getInstance(); // returns the instance
$a->get('users',array('username','=','ram')); // this return true or false
if(!$a->count()) {
echo "No User" ;
} else {
echo "OK " ;
}
Also you missed some $ at the ->action()
, it need to be:
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?" ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With