Database Code

  Home arrow Database Code arrow PiesDBO
DATABASE CODE

PiesDBO
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 1
    2004-09-16

    Table of Contents:

     
     

    SEARCH CODEWALKERS

    TOOLS YOU CAN USE

    advertisement
    A MySQL functions wrapper. Provides ability to get results as arrays and query logging (inc. execution time).

    By : jestempies

    <?PHP
    /*
    * Name: PiesDBO
    * Author: Michal Tatarynowicz (pies /at/ sputnik /dot/ pl)
    * Version: 1.0
    * Release date: 2004-09-16
    * Licence: Public Domain
    *
    * Description:
    * A MySQL functions wrapper. Provides ability to get results as arrays.
    *
    * Example usage:
    *
    require_once('dbo.inc');

    // create and connect the object
    $db = new PiesDBO(array(
    'host'=>'localhost',
    'user'=>'username',
    'pass'=>'password',
    'db'=>'database'));

    // read the whole query result array (of rows)
    $all_rows = $db->all("SELECT a,b,c FROM table");

    // read the first row with debugging on
    $first_row_only = $db->one("SELECT a,b,c FROM table WHERE a=1", TRUE);

    // emulate the usual MySQL way of reading query results
    if ( $db->q("SELECT a,b,c FROM table") ) {
    while ( $row = $db->farr() ) {
    print $row['a'].$row['b'].$row['c'];
    }
    }

    // show a log of all queries, sorted by execution time
    showLog(TRUE);

    */


    class PiesDBO {

    // public
    var $connected=FALSE;
    var $debug=FALSE;
    var $error=NULL;
    var $insert_id=NULL;
    var $affected=NULL;
    var $took=NULL;

    // private
    var $_conn=NULL;
    var $_result=NULL;
    var $_queries_cnt=0;
    var $_queries_time=NULL;
    var $_queries_log=array();


    function PiesDBO($config=NULL,$DEBUG=FALSE) {
    $this->__constructor($config);
    }

    function __constructor($config=NULL,$DEBUG=FALSE) {
    $this->debug = $DEBUG;
    Return $this->connect($config);
    }

    function __destructor() {
    $this->close();
    }

    function connect($config) {
    if($config) {
    $this->config = $config;
    $this->_conn = @mysql_connect($config['host'],$config['user'],$config['pass']);
    }

    $this->connected = $this->_conn? TRUE: FALSE;

    if($this->connected)
    Return @mysql_select_db($config['db'], $this->_conn);
    else
    Return $this->connected;
    }

    function close() {
    @mysql_close();
    showLog();
    $this->_conn = NULL;
    $this->connected = NULL;
    }


    function q($q,$DEBUG=FALSE) {
    Return $this->query($q,$DEBUG);
    }

    function query($q,$DEBUG=FALSE,$log=TRUE) {
    $t = getMicrotime();

    if($log){
    $this->_result = @mysql_query($q);
    $this->took = round(getmicrotime()-$t, 2);
    $this->error = mysql_errno()? mysql_errno().': '.mysql_error(): NULL;
    $this->insert_id = @mysql_insert_id();
    $this->affected = @mysql_affected_rows();
    $this->num_rows = @mysql_num_rows($this->_result);
    $this->_log_query($q);

    if($this->debug || $DEBUG) $this->_showQuery($q);

    Return $this->error? FALSE: $this->_result;
    }
    else
    Return @mysql_query($q);


    }


    function farr($results,$type=MYSQL_BOTH) {
    return mysql_fetch_array($results,$type);
    }


    function one($q,$DEBUG=FALSE,$type=MYSQL_BOTH) {
    Return $this->query($q,$DEBUG)? mysql_fetch_array($this->_result, $type): FALSE;
    }


    function all($q,$DEBUG=FALSE) {
    if($this->query($q,$DEBUG)) {
    $out=NULL;
    while($item = mysql_fetch_assoc($this->_result)) $out[] = $item;

    Return $out;
    }
    else {
    Return FALSE;
    }
    }


    function getConnected() {
    Return $this->connected;
    }


    function getInsertID() {
    Return $this->insert_id;
    }


    function getAffected() {
    Return $this->affected;
    }


    function getNumRows() {
    Return $this->num_rows;
    }


    function getError() {
    return $this->error;
    }


    function _log_query($q, $error=NULL) {
    $this->_queries_cnt++;
    $this->_queries_time += $this->took;
    $this->_queries_log[] = array(
    'query'=>$q,
    'error'=>$this->error,
    'affected'=>$this->affected,
    'num_rows'=>$this->num_rows,
    'took'=>$this->took
    );


    if ($this->error)
    logError("Query: {$q} RETURNS ERROR {$this->error}");
    }


    function showLog($sorted=FALSE) {

    $log = $sort_by_duration?
    sortByKey($this->_queries_log, 'took', 'desc', SORT_NUMERIC):
    $this->_queries_log;

    print("<table border=1>\n<tr><th colspan=7>{$this->_queries_cnt} queries took {$this->_queries_time} s</th></tr>\n");
    print("<tr><td>Nr</td><td>Query</td><td>Error</td><td>Affected</td><td>Num. rows</td><td>Took</td></tr>\n");

    foreach($log AS $k=>$i) {
    print("<tr><td>".($k+1)."</td><td align='left'>{$i['query']}</td><td>{$i['error']}</td><td>{$i['affected']}</td><td>{$i['num_rows']}</td><td>{$i['took']}</td></tr>\n");
    }

    print("</table>\n");
    }


    function _showQuery($q) {
    global $_DEBUG;

    $error = $this->error;

    if ($this->debug || $_DEBUG || $error) {
    print("<p style=\"text-align:left\"><b>Query:</b> {$q} <small>[Aff:{$this->affected} Num:{$this->num_rows} Took:{$this->took}s]</small>");
    if($error) {
    print("<br /><span style=\"color:Red;text-align:left\"><b>ERROR:</b> {$this->error}</span>");
    }
    print('</p>');
    }
    }
    }


    if (!function_exists('getMicrotime')) {
    function getMicrotime() {
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
    }
    }


    if (!function_exists('sortByKey')) {
    function sortByKey(&$array, $sortby, $order='asc', $type=SORT_NUMERIC) {

    if( is_array($array) ) {

    foreach( $array AS $key => $val )
    $sa[$key] = $val[$sortby];

    if( $order == 'asc' )
    asort($sa, $type);
    else
    arsort($sa, $type);

    foreach( $sa as $key=>$val )
    $out[] = $array[$key];

    Return $out;

    }
    else
    Return null;
    }
    }

    ?>
    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

    More Database Code Articles
    More By Codewalkers

    blog comments powered by Disqus

    DATABASE CODE ARTICLES

    - Converting CSV Files to MySQL Insert Queries...
    - Examples and Tools for Database Design
    - Relationships, Entities and Database Design
    - Modeling and Designing Databases
    - Data extract to Excel
    - Oracle database class 0.76
    - The opposite of mysql_fetch_assoc
    - On line Thermal Transmitance Calculation
    - pjjTextBase
    - PHP Object Generator
    - FastMySQL
    - RC4PHP
    - SQL function with integrated sprintf()
    - DB Interaction Classes v1.1
    - deeMySQLParser


    © 2003-2012 by Developer Shed. All rights reserved. DS Cluster 7 - Follow our Sitemap