PHP Classes

File: class.db.php

Recommend this page to a friend!
  Classes of JImmy Bo   Bobo PHP DB Class   class.db.php   Download  
File: class.db.php
Role: Class source
Content type: text/plain
Description: The class file for Bobo's PHP DB Class
Class: Bobo PHP DB Class
Simple MySQL database class
Author: By
Last change: - added update_from_array($table, $arr, $extra)
- added insert_from_array($table, $arr)
* examples for both the above functions are included below each functions code
Date: 10 years ago
Size: 12,419 bytes
 

Contents

Class file image Download
<?php /* Version 1.2 - added update_from_array($table, $arr, $extra) - added insert_from_array($table, $arr) * examples for both the above functions are included below each functions code */ /* Version 1.1 * Please leave this comment in at the top of the script if you use this script * in it's entirety. That is my only request. Other then that have fun. * http://www.phpclasses.org/package/5283-PHP-Simple-MySQL-database-access-wrapper.html * * I've often wondered why the database classes out there were really a little * cumbersome to work with. For me I value simplicity and power and have been * working on this little gem now for about 6 years with little tweaks here * and little tweaks there. I wasn't about to pack it with a gazillion features * but more just to kill off redundancy in my code. * * example usage: * * 1) create a file called inc.config.php in it throw this: * // include the class: * include_once('class.db.php'); * // set the variables: * $db_host = "localhost"; * $db_user = "myusername"; * $db_pass = "mypassword"; * $db_name = "mydatabasename"; * // make a db object: * $db = new mydb($db_host, $db_user, $db_pass, $db_name); * * 2) now in your file that you want to access the db from just include_once('inc.config.php'); * don't worry it won't connect till it's first query and it does so automagically. * * 3) some example usage: * // an insert * $SQL = "INSERT INTO addressbook (name) VALUES ('bob')"; * $insertid = $db->q($SQL); // returns false if no insertid or the id * echo $insertid; * * // a single row returned * $SQL = "SELECT * FROM addressbook WHERE name LIKE 'bob' LIMIT 1"; * $row = $db->row($SQL); * echo $row['name']; * * // multiple rows returned * $SQL = "SELECT * FROM addressbook"; * $addresses = $db->get($SQL); * foreach($addresses AS $address) * echo $address['name']; * * * * Also if you're looking for help from me directly you can usually find me * slumming it on #phphelp on the undernet irc network. * in that case I'd love to still hear from you at my email listed above. * * connection types: (can set on class init [mydb($host,$user,$pass, $db, $contype)]) or function set_contype($contype=0). If you call set_contype if there is a connection present it will reset it. -=-=-=-=-=-=-=-=-=-=- 1: Persistent Connection 2: Persistent Connection w/compression 3: Regular Connection w/compression 0: Regular Connection */ class mydb { var $host, $user, $pass, $db_name; var $contype; var $dlink; function mydb($host,$user,$pass, $db, $contype=0) { $this->host = $host; $this->user = $user; $this->pass = $pass; $this->db_name = $db; $this->contype = $contype; } function is_connected() { if(!isset($this->dlink) || empty($this->dlink)) return false; else return true; } function connect() { if($this->is_connected()) // check for open connection return 0; // connection exists :: bail switch($this->contype) { case 1: ###################################### Persistent Connection: $this->dlink = mysql_pconnect($this->host, $this->user, $this->pass) or die(mysql_error()."<hr /> :: in class db : 1-1"); break; case 2:####################### Persistent Connection with Compression: $this->dlink = mysql_pconnect ($this->host,$this->user, $this->pass,MYSQL_CLIENT_COMPRESS) or die(mysql_error()."<hr /> :: in class db : 1-2"); break; case 3: ######################### Regular Connection with Compression: $this->dlink = mysql_connect($this->host, $this->user, $this->pass, MYSQL_CLIENT_COMPRESS) or die(mysql_error()."<hr /> :: in class db : 1-3"); break; default: #################################### Regular Connection: $this->dlink = mysql_connect($this->host, $this->user, $this->pass) or die(mysql_error()."<hr /> :: in class db : 1-0"); break; } mysql_select_db($this->db_name) or die(mysql_error()."<hr /> :: in class db : 2"); return 1; } function set_contype($contype=0) { $oldtype = $this->contype; if($contype > 0 && $contype < 4) $this->contype = $contype; else $this->contype = 0; // check if there is a difference between the old connection type // and the new connection type. Then check to see if there is a connection // open and if so then close and reopen it. if($oldtype != $this->contype) { if($this->is_connected()) { $db->close(); $db->connect(); } } } function close() { if($this->is_connected()) { @mysql_close($this->dlink); $this->dlink = ""; return 1; } } function query($sql) { if(!$this->is_connected()) $this->connect(); mysql_query($sql) or die(mysql_error()."<hr /><pre>$sql</pre><hr /> :: in class db : 3"); return mysql_insert_id(); } function query_return($sql) { if(!$this->is_connected()) $this->connect(); $tempresult = mysql_query($sql) or die(mysql_error()."<hr /><pre>$sql</pre><hr /> :: in class db : 4"); while ($row = mysql_fetch_array($tempresult, MYSQL_ASSOC)) $result[] = $row; mysql_free_result($tempresult); return @$result; } function table_exists($table) { if(!$this->is_connected()) $this->connect(); $exists = mysql_query('SHOW TABLES FROM `'.$this->db_name.'` LIKE \''.$table.'\''); if(mysql_num_rows($exists) == 1) return true; else return false; } function insert_id() { return mysql_insert_id(); } # this will return just the first row of returned data function row($sql) { if(!$DATA = $this->get($sql)) return false; else return $DATA[0]; } # ####### BEGIN Cache Writing Magic... function flush_buffers() { ob_end_flush(); ob_flush(); flush(); ob_start(); } // 2d array to PHP // function rows_to_php($arr, $var = '$arr') { $str = '<?php'."\r\n"; // takes a simple 2d arr and formats for a flatfile if(is_array($arr)) { foreach($arr as $a) { if(is_array($a)) { $count = 0; $str .= $var.'[]=array('; foreach($a as $key=>$value) { if($count > 0) $str .= ','; $value = str_replace('\"', '^{~||~}^', $value); $value = str_replace('"', '^{~||~}^', $value); $value = str_replace('^{~||~}^', '\"', $value); $str .= '"'.$key.'"=>"'.$value.'"'; $count++; } $str .= ');'."\r\n"; } } } $str .= '?>'; return $str; } // END 2d array to PHP // // 1d array to PHP // function row_to_php($arr, $var = '$arr') { $str = '<?php'."\r\n"; $a = $arr; // takes a simple 1d arr and formats for a flatfile if(is_array($a)) { $count = 0; $str .= $var.'[]=array('; foreach($a as $key=>$value) { if($count > 0) $str .= ','; // song and dance... woop de woo... $value = str_replace('\"', '^{~||~}^', $value); $value = str_replace('"', '^{~||~}^', $value); $value = str_replace('^{~||~}^', '\"', $value); $str .= '"'.$key.'"=>"'.$value.'"'; $count++; } $str .= ');'."\r\n"; } $str .= '?>'; return $str; } // END 1d array to PHP // function row_to_file($cachefile, $sql, $var, $timer) { // $var is the array variable name for the cache file... eg) $var = '$users' // so in the cachefile it would be $users[] = array (); ... capiche? // $timer is in seconds... $nextupdate = @filemtime($cachefile) + $timer; // get current file time + timer time... // is our data old? if so make it happen if(time() >= $nextupdate || !file_exists($cachefile)) { $arr = $this->row($sql); $data = $this->row_to_php($arr, $var); file_put_contents($cachefile, $data); @$this->flush_buffers(); return true; } } function rows_to_file($cachefile, $sql, $var, $timer) { // $var is the array variable name for the cache file... eg) $var = '$users' // so in the cachefile it would be $users[] = array (); ... capiche? // $timer is in seconds... $nextupdate = @filemtime($cachefile) + $timer; // get current file time + timer time... // is our data old? if so make it happen if(time() >= $nextupdate || !file_exists($cachefile)) { $arr = $this->get($sql); $data = $this->rows_to_php($arr, $var); file_put_contents($cachefile, $data); @$this->flush_buffers(); return true; } } # ####### END Cache Writing Magic... // new aliases .. function q($sql) { return $this->query($sql); } function get($sql) { return $this->query_return($sql); } function r($sql) { return $this->row($sql); } // yes I'm sure this one can be super duper optimized. function safe_text($text) // convert special characters into html escape codes { $text = mysql_real_escape_string($text); return $text; } // will take the javascript out of your text function remove_js($text) { return preg_replace("/<script[^>]*>.*?< *script[^>]*>/i", "", $text); } // will take the html out of your text function remove_html($text) { return strip_tags($text); } // new functions that will help clean up main programs code/eliminate some redundancy/and make // updates and inserts more uniform... takes an array of key value pairs and either updates // or runs an insert operation. Returns insert id on the insert function function update_from_array($table, $arr, $extra) { if(!is_array($arr) || empty($table)) return false; $first = true; $sql = "UPDATE $table SET "; foreach($arr as $key => $value) { if(!$first) $sql .= ","; $sql .= $key."="."'$value' "; $first = false; } $sql .= $extra; return $this->q($sql); } ## EXAMPLE UPDATE ## /* global $db; $table = 'tblorderpcs'; $extra = "WHERE jID = $subjobid LIMIT 1"; $arr = array ( "pcs_name" => $sname, "pcs_qty" => $sqty, "pcs_pn" => $spn, "pcs_estimate" => $sest, "pcs_memo" => $smemo, "ship_id" => $ship_id, "pcs_made" => $smade, "pcs_wasted"=> $swasted, "pcs_ppu" => $sppu ); return $db->update_from_array($table, $arr, $extra); */ function insert_from_array($table, $arr) { if(!is_array($arr) || empty($table)) return false; $key_str = ''; $val_str = ''; $sql_start = "\r\nINSERT INTO $table ( "; $sql_mid = " ) VALUES ( "; $sql_end = " ); \r\n"; $first = true; foreach($arr as $key => $value) { if(!$first) { $key_str .= ","; $val_str .= ","; } $key_str .= "$key"; $val_str .= "'$value'"; $first = false; } $sql = $sql_start.$key_str.$sql_mid.$val_str.$sql_end; $id = $this->q($sql); return $id; } ## EXAMPLE INSERT ## /* global $db; $time = time(); $table = 'tblorderpcs'; $arr = array ( "order_id" => $jobid, "pcs_name" => $sname, "pcs_qty" => $sqty, "pcs_pn" => $spn, "pcs_estimate" => $sest, "pcs_memo" => $smemo, "ship_id" => $ship_id, "pcs_tstamp" => $time ); return $db->insert_from_array($table, $arr); */ } ?>