Database Code
  Home arrow Database Code arrow PiesDBO
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  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Download TestComplete 
Forums Sitemap 
Weekly Newsletter 
 
Developer Updates  
Free Website Content 
 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


    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! "ebook: Exploring IBM SOA Technology & Practice

    Learn field-tested SOA principles, methodology, technology and implementation from the global SOA market leader - in a new e-book by an IBM SOA expert. Written by IBM Certified SOA Solution Designer Bobby Woolf, "Exploring IBM SOA Technology & Practice" is the ultimate insider's guide to SOA - a PDF e-book packed cover to cover with IBM's specific advice on how to make your SOA implementation a success.
    FREE! Go There Now!


    NEW! Best practices for software analysis: An introduction to the IBM Rational Software Analyzer application

    This whitepaper presents the benefits of successfully introducing static analysis into your organization using IBM Rational Software Analyzer. Additionally, it identifies some common pitfalls that can hinder the effective use of static analysis tooling as well as presents 10 simple strategies designed to help you quickly realize the value of static analysis using Rational Software Analyzer.
    FREE! Go There Now!


    NEW! Discovering the value of WebSphere Process Server

    WebSphere Process Server delivers a unique integration framework that simplifies existing IT resources. Often, as IT assets grow to support business demand, so too does their complexity and manageability. In this webcast, we’ll discuss how WebSphere Process Server helps deliver an SOA infrastructure that provides a common model to orchestrate, mediate, connect, map, and execute the underlying IT functions. Discover how WebSphere Process Server simplifies integration of business processes by leveraging existing IT assets as reusable services without the complexities of traditional integration methodologies.
    FREE! Go There Now!


    NEW! Download IBM Data Studio V1.1

    Visit IBM developerWorks to download the latest trial version of IBM Data Studio V1.1 at no cost. IBM Data Studio is a comprehensive data management solution that helps you effectively design, develop, deploy and manage your data, databases, and database applications throughout the data management life cycle utilizing a consistent and integrated user interface. Unlike other client-side data management solutions that focus on only one aspect of the application lifecycle or database administration, Data Studio complements the Rational Software Delivery platform, providing unparalleled flexibility for a heterogeneous data server environment across platforms.
    FREE! Go There Now!


    NEW! Harnessing the power of SQL and Java for high performance data access

    Join this webcast to see how IBM Data Studio Developer and pureQuery can take the pain out of Java data access. uApplications developed using both Java and SQL have become a common requirement. Database connectivity using Java Database Connectivity (JDBC) to create an application is a multi-step tedious process, and tooling that covers both SQL and Java has been unavailable, until now. IBM Data Studio introduces the pureQuery platform: a high-performance, Java data access platform focused on simplifying the tasks of developing, managing, and optimizing database applications and services.
    FREE! Go There Now!


    NEW! Hello World: Monitor a simple business process using WebSphere Business Monitor V6.0.2

    This tutorial shows new users of IBM WebSphere Business Monitor Version 6.0.2 how to perform the "Hello World" equivalent for monitoring business process applications. It is intended to help you get familiar with the capabilities of the product.
    FREE! Go There Now!


    NEW! Krugle, developerWorks, and code search

    Ken Krugler, co-founder of code search company Krugle, and Laura Merling, vice president of Marketing and Business Development for Krugle, join to talk about the ins and outs of code search and what it means as a new feature for developerWorks users.
    FREE! Go There Now!


    NEW! Trial download: IBM Rational Performance Tester V7.0.1

    Get a free trial download of the latest version of IBM Rational Performance Tester V7.0.1, a load and performance testing solution for teams concerned about the scalability of their Web-based applications. Combining multiple ease-of-use features with granular detail, Rational Performance Tester simplifies the test-creation, load-generation and data-collection processes that help teams ensure the ability of their applications to accommodate required user loads.
    FREE! Go There Now!


    NEW! Using Rational Business Developer to enhance your developer productivity

    Join this Rational Talks to You teleconference, to hear how Enterprise Generation Language (EGL) eliminates the need for tedious and error-prone low level coding, so developers can focus on business requirements. EGL extends the Rational software development platform with a simplified programming language that enables developers who have little or no experience with Java, Web technologies or Service Oriented Architecture, to create enterprise-class applications and services quickly and easily. It also allows developers who may have little or no mainframe programming experience to quickly create traditional mainframe components.
    FREE! Go There Now!


    NEW! Webcast: Extreme transaction processing with WebSphere Extended Deployment

    In this webcast, you'll get an introduction to the eXtreme Transaction Processing (XTP) features of WebSphere Extended Deployment and the common architectural traits required by XTP applications. See how WebSphere Extended Deployment's ObjectGrid feature provides a state-of-the-art infrastructure for hosting XTP 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-2010 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek