Database Code
  Home arrow Database Code arrow PiesDBO
Try It Free
Codewalker Forums 
  Tutorials  
Database Articles  
Miscellaneous  
Navigation Usability  
PEAR Articles  
Programming Basics  
Server Administration  
XML Tutorials  
  Reviews  
Database Book Reviews  
Linux Book Reviews  
Miscellaneous Reviews  
PHP Book Reviews  
PHP Software Reviews  
Server Admin Reviews  
SQL Tool Reviews  
  Code Gallery  
Content Management Code  
Contest Code  
Counters Code  
Database Code  
Date Time Code  
Discussion Board Code  
Email Code  
File Manipulation Code  
GUI Code  
Link Farm Code  
Miscellaneous Code  
Search Code  
Site Navigation Code  
User Management Code  
Forums Sitemap 
Dedicated Servers  
Download TestComplete 
IBM® developerWorks
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
IBM developerWorks
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
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:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    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

     

    IBM® developerWorks developerWorks - FREE Tools!


    NEW! Calling all CC Power Users – and those that would like to be!

    Join this Rational Talks to You teleconference, featuring Paul Boustany and Mark Krasovich, to speak to the experts about becoming a Rational ClearCase power user. Get a chance to ask your questions and learn tips and tricks for using Rational ClearCase in Agile development
    FREE! Go There Now!


    NEW! IBM – Taking Web 2.0 to Work

    David Barnes, Lead Evangelist for IBM Emerging Internet Technologies will discuss aspects of Web 2.0 that bring value to corporations, academia, and government. He'll also discuss IBM's vision around Web 2.0, including the importance of remixability and consumability. The discussion will culminate with examples of various IBM Software Group solutions you can use to get ahead of the Web 2.0 adoption curve.
    FREE! Go There Now!


    NEW! Evaluate IBM Rational Software Analyzer V7.0

    Download a free trial version of IBM Rational Software Analyzer Developer Edition V7.0 to identify bug defects earlier in the software development cycle. Rational Software Analyzer is an extensible software development solution that reduces the expense of bug-fixes by enabling static analysis code reviews and bug identification very early in the development cycle.
    FREE! Go There Now!


    NEW! Evaluate Rational Host Access Transformation Services (HATS) Toolkit V7.1

    Visit IBM developerWorks to download a free trial of the Rational Host Access Transformation Services (HATS) Toolkit. The HATS toolkit provides a set of plug-ins for the IBM Rational Software Delivery Platform to help you easily extend your legacy applications. HATS makes your 3270 and 5250 applications available as HTML through the most popular Web browsers, while converting your host screens to a Web look and feel and it also enables you to develop new Web, portal, and rich-client applications.
    FREE! Go There Now!


    NEW! Hello World: Learn how to install and use the Rational Asset Manager Eclipse client

    In this tutorial, you can learn how to install and configure the IBM Rational Asset Manager Eclipse client, explore the different views in the Asset Management perspective, learn various search techniques, work with existing assets, and submit a new asset.
    FREE! Go There Now!


    NEW! Improve your build process with IBM Rational Build Forge, Part 1: Create a continuous build and integration environment

    Learn how to implement a build management system that uses and extends your existing automation technologies. This tutorial shows, step-by-step, how to install and configure IBM Rational Build Forge to manage builds for Jakarta Tomcat from source code.
    FREE! Go There Now!


    NEW! Webcast: IBM Rational Build Forge - Beyond the Build

    The discipline of assembling and delivering software is maturing beyond standard developer-centric compile/test software builds. The end-to-end software development lifecycle is emerging as the new focus moves “Beyond the Build.” Join this on demand webcast to learn about methods for streamlining software delivery and key capabilities of the IBM Rational Build Forge framework for automating build and release management in environments of any size.
    FREE! Go There Now!


    NEW! Webcast: Introducing the new Information Server and Solutions community: LeverageInformation

    User communities play an important role in communication and collaboration around products, solutions and other areas of special interest to members. Successful communities are able to provide the right mix of content and services to deliver a value proposition that resonates with each audience. Join Tom Inman, VP of Marketing for Information and Platform Solutions as he introduces the new LeverageINFORMATION community. During this webcast, learn about the value provided by the community and how customers and partners derive value from the community in addressing their own technical and business challenges.
    FREE! Go There Now!


    NEW! Webcast: Striking the right balance between manual and automated testing

    Join this webcast to learn how IBM Rational's Functional Testing solution enables you to implement automation your way, at your pace, with your existing staff. In this webcast, you’ll learn how you can eliminate redundancy of manual test scripts, reduce errors, and increase test coverage through test automation. After this presentation you will understand how IBM Rational Functional Testing solution can streamline your manual testing and make test automation easily attainable.
    FREE! Go There Now!


    NEW! Webcast: What is new in Viper 2 for developers?

    Viper 2 brings a great value to developer communities including SQL, XML, PHP, Ruby, .NET and Java. You probably already know that DB2 Express-C is free for developers to develop, deploy and distribute. Viper 2 provides a variety of means that help move your application from the development stage to deployment more rapidly. This webcast shows how to best utilize the latest tools available for developing DB2 applications.
    FREE! Go There Now!



    All FREE IBM® developerWorks Tools!

    DATABASE CODE ARTICLES

    - 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
    - CSV to SQL convertor





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 2 hosted by Hostway