So I am on a mission to learn how to create DB classes of my own using PDO. I am fairly new to PDO and more complex class development and wanted to get a little guidance from the community before I get too far into it. I have a class partially built but I know there has to be a better/more logical way to do this.
I'd really like to be able to have a single query method so I can trow almost anything at it in my DB class. If this is faulty thinking please let me know why.
Currently I have a config.php file with DB constants defined and a class called DB. Here's my Code:
In index.php:
require_once 'config.php';
require_once '_inc/class.db.php';
$db = new DB();
And my class:
public $dbh;
public function __construct(){
$dbh = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWORD);
}//end __construct
public function build_query( $args ){
$defaults = array(
'type' => 'SELECT',
'fields' => '*',
'table' => '',
'where' => '',
'orderby' => 'id',
'order' => 'DESC'
'offset' => '0',
'limit' => ''
);
$params = array_merge( $defaults, $args );
$sql = $params['type'];
$sql .= ' '.$params['fields'].' FROM '.$params['table'];
if( $params['where'] )
$sql .= ' WHERE '.$params['where'];
$sql .= ' ORDER BY '$params['orderby'].' '.$params['order'];
if( $limit )
$sql .= ' LIMIT '.$params['offset'].', '.$params['offset'];
return $sql;
}//end build_query
public function dbq( $args ){
$sql = $this->build_query( $args );
$this->$dbh->prepare( $sql );
return $this->$dbh->execute();
I know I am missing something here. Please just push me in the right direction as I really want to learn this to become a better PHP developer. I did look a little at using singleton pattern but wanted to get a little more info from people who really know how it all works and fits together.
Thanks in advance!