WeberDev.com PHP and MySQL Code

LOG IN
BEGINNER GUIDESPHP CLASSESCODE SEARCHARTICLES SEARCHPHP FORUMSPHP MANUALPHP FUNCTIONS LISTWEB SITE TEMPLATES
Start typing to search for PHP and MySQL Code Snippets and Articles Search
Submit a code Example / Snippet Join us on FaceBook
Submit a code Example / Snippet Submit Your Code
Poker Tournaments Poker Tournaments
Poker Guide for Developers Poker Guide for Developers
Search Engine Optimization Monitor SEO Monitor
Web Site UpTime Monitor UpTime Monitor
Your Personal Examples List My Favorite Examples
Your Personal Articles List My Favorite Articles
Edit Account Info Update Your Profile
PHP Code Search
Web Development Forums
Learn MySQL Playing Trivia
PHPBB2 Templates
Web Development Resources
Web Development Content
Internet Security Software
PHPClasses
PHP Editor
PHP Jobs
Vision.To Design
Ajax Tutorials
PHP Programming Help
PHP/MySQL Programming
Webmaster Resources
Webmaster Forum
XML meta language
website builder
פרייסז - הכח לקנות עובר לידיים שלך
Texas Holdem Poker Evangelists

Go Back Add a Comment Send this example to a friend Add this Article to your personal favoritest for easy future access to your favorite Code Examples and Articles. Submit a code example Print this code example.
BACK ADD A COMMENT SEND TO A FRIEND ADD TO MY FAVORITES ADD CODE EXAMPLES PRINT
Title : PDO Wrapper
Categories : PHP, PHP Classes, Databases, MySQL Click here to Update Your Picture
Vinod Mohan
Date : Dec 09th 2008
Grade : 3 of 5 (graded 2 times)
Viewed : 6460
File : No file for this code example.
Images : No Images for this code example.
Search : More code by Vinod Mohan
Action : Grade This Code Example
Tools : My Examples List

Submit your own code examples  Submit your own code examples 
 

An easy to use PDO wrapper class. Includes methods like

PDO::getRecord()
PDO::insertRecord()
PDO::updateRecord()
PDO::getQuery()

for easy coding and better error control. Please let me know your comments.
<?php
class extendedPDO extends PDO{
    private
$arQuery = array();
   
/*
    Parameters same as original PDO::exec
    */   
   
public function exec($statement){
        if(!empty(
$statement)){
            try{
               
$result = parent::exec($statement);
                if(
$result === FALSE)$this->triggerError();
            }catch(
PDOException $e){
               
$this->triggerError($e);
            }
           
$this->arQuery[] = $statement;
            return
$result;
        }else{
            return
FALSE;
        }
    }
   
/*
    Parameters same as original PDO::query
    */
   
public function query($statement, $fetchMode = null, $objORClassnameORColNo = null, $ctorargs = null){
        if(!empty(
$statement)){
            try{
               
$this->stmt = parent::query($statement, $fetchMode, $objORClassnameORColNo, $ctorargs);
               
$this->arQuery[] = $statement;
                if(
$this->stmt === FALSE)$this->triggerError();
            }catch(
PDOException $e){
               
$this->triggerError($e);
            }
            return
$this->stmt;
        }else{
            return
FALSE;
        }
    }
   
/*
    Function to return previously executed query
    @param - The index of the query. If none is provided, then last query is returned
    */
   
public function getQuery($idx = null){
        if(empty(
$this->arQuery))return false;
        if(
is_null($idx)){
           
$idx = count($this->arQuery) - 1;
        }
        return
$this->arQuery[$idx];
    }
   
/*
    Function to retrieve existing row(s) from the database
    @param $tblName - DB Table Name
    @param $conditions - Condition for updation as associative array(eg. array('id' => ))
    @param $values - the value to be inserted as an associative array (eg. array('id' => 1, 'uid' => '007', 'name' => 'James Bond'))
    @param $limit - Number of rows to retrieve. If $limit is null, then all matching rows are retrieved. If $row is an array, say array( 50, 10)
                    Then rows 50 - 60 will be returned. If limit is 1, then result is returned as an associative array
    */
   
function getRecord($tblName, $conditions, $limit = 1){
       
$whereSql = $this->_getWhereSQL($conditions);
       
$limitSql = $this->_getLimitSQL($limit);
       
$stmt = $this->query("SELECT * FROM $tblName $whereSql $limitSql");
        if(
$stmt !== FALSE && $limit == 1){
            return
$stmt->fetch(PDO::FETCH_ASSOC);
        }else{
            return
$stmt;
        }
    }
   
/*
    Function to insert a new row into the database
    @param $tblName - DB Table Name
    @param $values - the value to be inserted as an associative array (eg. array('id' => 1, 'uid' => '007', 'name' => 'James Bond'))
    */
   
public function insertRecord($tblName, $values) {
       
$keys = array_keys($values);
       
$fields = '(`' . implode('`, `', $keys) . '`)';
       
$values = '(' . implode(', ', array_map(array($this, 'quote'), $values)) . ")";
        return
$this->exec("INSERT INTO `$tblName` $fields VALUES $values");
    }
   
/*
    Function to update an existing row in the database
    @param $tblName - DB Table Name
    @param $conditions - Condition for updation as associative array(eg. array('id' => ))
    @param $values - the value to be inserted as an associative array (eg. array('id' => 1, 'uid' => '007', 'name' => 'James Bond'))
    @param $limit - Number of rows to update. If $limit is null, then all matching rows are updated. If $row is an array, say array( 50, 10)
                    Then rows 50 - 60 will be updated
    */
   
public function updateRecord($tblName, $conditions, $values, $limit = 1) {
       
$fields = $this->_getValues($values);
       
$whereSql = $this->_getWhereSQL($conditions);
       
$limitSql = $this->_getLimitSQL($limit);
        return
$this->exec("UPDATE `$tblName` SET $fields $whereSql $limitSql");
    }
    function
triggerError($e = FALSE){
       
// Here do your error management procedures
        // You may sent a notification mail with the error details
       
echo "<br/><b>Database Error:</b> ";
        if(
$e){
            echo
$e->getMessage();
        }else{
           
$errorInfo = $this->errorInfo();
            echo
"[$errorInfo[1]] $errorInfo[2]";
        }
        exit;
    }
    private function
_getValues($values = null){
        if(
is_null($values)){
           
$values = '';
        }elseif(
is_array($values)){
           
$arField = array();
            foreach(
$values as $field => $value){
               
$value = $this->quote($value);
               
$arField[] = "`$field` = $value";
            }
           
$values = implode(', ', $arField);
        }else{
           
$values = '';
        }   
        return
$values;
    }
    private function
_getWhereSQL($condition){
       
//$condition = $this->_getCondition($condition);
       
if(is_null($condition)){
           
$values = '';
        }elseif(
is_array($condition)){
           
$arField = array();
            foreach(
$condition as $field => $value){
               
$value = $this->quote($value);
               
$arField[] = "`$field` = $value";
            }
           
$condition = 'WHERE ' . implode(' AND ', $arField);
        }else{
           
$condition = '';
        }
        return
$condition;
    }
    private function
_getLimitSQL($limit = null){
        if(
is_null($limit)){
           
$limit = '';
        }elseif(
is_array($limit)){
           
$limit = "LIMIT $limit[0], $limit[1]";
        }else{
           
$limit = "LIMIT $limit";
        }
        return
$limit;
    }
}

?>




DB Schema
CREATE TABLE `test`.`weber_test` (
`id` INT( 5 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`title` VARCHAR( 255 ) NOT NULL ,
`author` VARCHAR( 50 ) NOT NULL ,
`price` VARCHAR( 5 ) NOT NULL
) ENGINE = MYISAM



example usage
<?php
$dbType
= 'mysql';
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = '';
$dbName = 'test';
$pdo = new extendedPDO("$dbType:host=$dbHost;port=4040;dbname=$dbName", $dbUser, $dbPass, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

$pdo->insertRecord('weber_test', array('title' => 'Around the World in 80 Days', 'author' => 'Julie Verne', 'price' => '$90'));
$id = $pdo->lastInsertId();
$pdo->updateRecord('weber_test', array('id' => $id), array('author' => 'Jules Verne', 'price' => '$' . mt_rand(0, 500) ));
$record = $pdo->getRecord('weber_test', array('id' => $id));

print <<<HERE
Inserted Data<br/>
ID :
$id<br/>
Title :
{$record['title']}<br/>
Author :
{$record['author']}<br/>
Price :
{$record['price']}<br/><br/>
HERE;

$stmt = $pdo->getRecord('weber_test', null, null);
if(
$stmt){
    echo
'<table>';
   
$stmt->setFetchMode(PDO::FETCH_ASSOC);
    while(
$record = $stmt->fetch()){
        echo
"<tr><td>{$record['id']}</td><td>{$record['title']}</td><td>{$record['author']}</td><td>{$record['price']}</td></tr>";
    }
    echo
'</table>';
}
?>


MySQL's native prepared statements cannot take advantage of the Query Cache. Fortunately, in PHP 5.1.3 release and above there is a work around. Set the attribute PDO::ATTR_EMULATE_PREPARES to true.

<?php
$pdo
->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
?>



Setting up InnoDB on MySQL and using Transactions Begin, Commit, Rollback in PHP.
Categories : PHP Classes, Databases, PHP, MySQL, InnoDB
PostGreSQL and MySQL 2 in 1 db Manager
Categories : PHP, PHP Classes, Databases, PostgreSQL, MySQL
MySQL Class to ease Database connectivity
Categories : MySQL, PHP Classes, Databases, PHP
[PHP5] aDB PDO LIKE Database Abstraction. Switch easily from one db server to another, strong errors management, manage transactions, queries preparation and more.
Categories : PHP, PHP Classes, Databases, MS SQL Server, MySQL
Online Automatic Class Generator for MySQL Tables
Categories : PHP, PHP Classes, Classes and Objects, Databases, MySQL
Create and restore backup of MySQL databases
Categories : MySQL, Databases, PHP, PHP Classes, Complete Programs
bookmarker - PHP, PHPLIB, MySQL WWW based bookmark manager
Categories : MySQL, PHP, MySQL, Complete Programs, Databases
Password reminder
Categories : PHP, PHP Classes, Databases, MySQL, Mail
DBXML- A Class to backup databases in XML Format using web interface
Categories : PHP, PHP Classes, Databases, MySQL, XML
phpFormGenerator for Dynamic Form Generation from MySQL
Categories : PHP, PHP Classes, MySQL, Databases, HTML and PHP
MySQL database class
Categories : PHP, MySQL, Databases, PHP Classes
Ajax PHP Tree (Left and Right) with MySQL
Categories : PHP, Databases, MySQL, AJAX, PHP Classes
PHP Object Example of the Perl DBI with MySQL
Categories : PHP, PHP Classes, MySQL, Databases, Perl
Convert SQL from oracle,mysql,mssql,sqlite and odbc to SQL compatible
Categories : PHP, PHP Classes, Databases, MySQL, MS SQL Server
usercounter class
Categories : PHP, PHP Classes, Databases, MySQL, Environment Variables