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
developerWorks - FREE Tools! |
You'll get answers to many questions and more from David Barnes, Lead Evangelist for IBM Emerging Internet Technologies. David 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!
|
|
|
|
Building a software-as-a-service solution requires addressing a few key technical challenges. In this webcast, we'll focus on the role of IBM Tivoli Directory Server and WebSphere Portlet Factory in creating a Software as a Service solution. We will demonstrate how to use Tivoli Directory Server to prevent the user population of one tenant from accessing the virtual portal and portlet components of another tenant. We will also use the dynamic profile capability of WebSphere Portlet Factory to create multiple highly customized applications from one code base. FREE! Go There Now!
|
|
|
|
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!
|
|
|
|
Discover how IBM Rational AppScan Standard Edition can help you detext vulnerabilities in your web applications in the Web Application Security eKit. IBM Rational AppScan is a leading suite of automated web application security solutions that scan and test for common Web application vulnerabilities. The new Web Application Security eKit provides you with valuable resources, including white papers, demos, and additional information on the benefits of testing your Web applications. FREE! Go There Now!
|
|
|
|
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!
|
|
|
|
Manage, govern, and share services across your organization by using WebSphere Service Registry and Repository. Follow the hands-on exercises to learn how to navigate the Web interface to publish, find, reuse, and update services. FREE! Go There Now!
|
|
|
|
Learn how to do more with your reusable assets with the free Rational Asset Manager eKit. The eKit includes demos on how Rational Asset Manager tracks and audits your assets in order to utilize them for reuse. Plus you’ll find white papers and a Webcast that discuss the challenges of a Service Oriented Architecture and how Rational Asset Manager can provide quick and effective solutions. FREE! Go There Now!
|
|
|
|
Learn the basics of the IBM Customer Information Control System (CICS). With a hands-on exercise, learn how to get your first CICS application up and running on your desktop using TXSeries V6.1 for Windows. The tutorial shows you how to download and install a free trial version of TXSeries V6.1. FREE! Go There Now!
|
|
|
|
Try the latest version of IBM Rational Manual Tester V7.0.1 by downloading a free trial from IBM developerWorks. This manual test authoring and execution tool promotes test step reuse to reduce the impact of software change on testers and business analysts and addresses the needs of teams performing at least a portion of their testing manually. FREE! Go There Now!
|
|
|
|
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!
|
|
|
|
All FREE IBM® developerWorks Tools! |