3 /**********************************************************************
4 * Author: Justin Vincent (jv@vip.ie)
5 * Web...: http://justinvincent.com
7 * Desc..: ezSQL Core module - database abstraction library to make
8 * it very easy to deal with databases. ezSQLcore can not be used by
9 * itself (it is designed for use by database specific modules).
13 /**********************************************************************
17 define('EZSQL_VERSION','2.17');
18 define('OBJECT','OBJECT',true);
19 define('ARRAY_A','ARRAY_A',true);
20 define('ARRAY_N','ARRAY_N',true);
22 /**********************************************************************
23 * Core class containg common functions to manipulate query result
30 var $trace = false; // same as $debug_all
31 var $debug_all = false; // same as $trace
32 var $debug_called = false;
33 var $vardump_called = false;
34 var $show_errors = true;
36 var $last_query = null;
37 var $last_error = null;
39 var $captured_errors = array();
40 var $cache_dir = false;
41 var $cache_queries = false;
42 var $cache_inserts = false;
43 var $use_disk_cache = false;
44 var $cache_timeout = 24; // hours
45 var $timers = array();
46 var $total_query_time = 0;
47 var $db_connect_time = 0;
48 var $trace_log = array();
49 var $use_trace_log = false;
50 var $sql_log_file = false;
51 var $do_profile = false;
52 var $profile_times = array();
54 // == TJH == default now needed for echo of debug function
55 var $debug_echo_is_on = true;
57 /**********************************************************************
61 function __construct()
65 /**********************************************************************
66 * Get host and port from an "host:port" notation.
67 * Returns array of host and port. If port is omitted, returns $default
70 function get_host_port( $host, $default = false )
73 if ( false !== strpos( $host, ':' ) ) {
74 list( $host, $port ) = explode( ':', $host );
77 return array( $host, $port );
80 /**********************************************************************
81 * Print SQL/DB error - over-ridden by specific DB class
84 function register_error($err_str)
86 // Keep track of last error
87 $this->last_error = $err_str;
89 // Capture all errors to an error array no matter what happens
90 $this->captured_errors[] = array
92 'error_str' => $err_str,
93 'query' => $this->last_query
97 /**********************************************************************
98 * Turn error handling on or off..
101 function show_errors()
103 $this->show_errors = true;
106 function hide_errors()
108 $this->show_errors = false;
111 /**********************************************************************
112 * Kill cached query results
118 $this->last_result = null;
119 $this->col_info = null;
120 $this->last_query = null;
121 $this->from_disk_cache = false;
124 /**********************************************************************
125 * Get one variable from the DB - see docs for more detail
128 function get_var($query=null,$x=0,$y=0)
131 // Log how the function was called
132 $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
134 // If there is a query then perform it if not then use cached results..
137 $this->query($query);
140 // Extract var out of cached results based x,y vals
141 if ( $this->last_result[$y] )
143 $values = array_values(get_object_vars($this->last_result[$y]));
146 // If there is a value return it else return null
147 return (isset($values[$x]) && $values[$x]!=='')?$values[$x]:null;
150 /**********************************************************************
151 * Get one row from the DB - see docs for more detail
154 function get_row($query=null,$output=OBJECT,$y=0)
157 // Log how the function was called
158 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
160 // If there is a query then perform it if not then use cached results..
163 $this->query($query);
166 // If the output is an object then return object using the row offset..
167 if ( $output == OBJECT )
169 return $this->last_result[$y]?$this->last_result[$y]:null;
171 // If the output is an associative array then return row as such..
172 elseif ( $output == ARRAY_A )
174 return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null;
176 // If the output is an numerical array then return row as such..
177 elseif ( $output == ARRAY_N )
179 return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null;
181 // If invalid output type was specified..
184 $this->show_errors ? trigger_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N",E_USER_WARNING) : null;
189 /**********************************************************************
190 * Function to get 1 column from the cached result set based in X index
191 * see docs for usage and info
194 function get_col($query=null,$x=0)
197 $new_array = array();
199 // If there is a query then perform it if not then use cached results..
202 $this->query($query);
205 // Extract the column values
206 for ( $i=0; $i < count($this->last_result); $i++ )
208 $new_array[$i] = $this->get_var(null,$x,$i);
215 /**********************************************************************
216 * Return the the query as a result set - see docs for more details
219 function get_results($query=null, $output = OBJECT)
222 // Log how the function was called
223 $this->func_call = "\$db->get_results(\"$query\", $output)";
225 // If there is a query then perform it if not then use cached results..
228 $this->query($query);
231 // Send back array of objects. Each row is an object
232 if ( $output == OBJECT )
234 return $this->last_result;
236 elseif ( $output == ARRAY_A || $output == ARRAY_N )
238 if ( $this->last_result )
241 foreach( $this->last_result as $row )
244 $new_array[$i] = get_object_vars($row);
246 if ( $output == ARRAY_N )
248 $new_array[$i] = array_values($new_array[$i]);
264 /**********************************************************************
265 * Function to get column meta data info pertaining to the last query
266 * see docs for more info and usage
269 function get_col_info($info_type="name",$col_offset=-1)
272 if ( $this->col_info )
274 if ( $col_offset == -1 )
277 foreach($this->col_info as $col )
279 $new_array[$i] = $col->{$info_type};
286 return $this->col_info[$col_offset]->{$info_type};
293 /**********************************************************************
297 function store_cache($query,$is_insert)
300 // The would be cache file for this query
301 $cache_file = $this->cache_dir.'/'.md5($query);
303 // disk caching of queries
304 if ( $this->use_disk_cache && ( $this->cache_queries && ! $is_insert ) || ( $this->cache_inserts && $is_insert ))
306 if ( ! is_dir($this->cache_dir) )
308 $this->register_error("Could not open cache dir: $this->cache_dir");
309 $this->show_errors ? trigger_error("Could not open cache dir: $this->cache_dir",E_USER_WARNING) : null;
313 // Cache all result values
314 $result_cache = array
316 'col_info' => $this->col_info,
317 'last_result' => $this->last_result,
318 'num_rows' => $this->num_rows,
319 'return_value' => $this->num_rows,
321 file_put_contents($cache_file, serialize($result_cache));
322 if( file_exists($cache_file . ".updating") )
323 unlink($cache_file . ".updating");
329 /**********************************************************************
333 function get_cache($query)
336 // The would be cache file for this query
337 $cache_file = $this->cache_dir.'/'.md5($query);
339 // Try to get previously cached version
340 if ( $this->use_disk_cache && file_exists($cache_file) )
342 // Only use this cache file if less than 'cache_timeout' (hours)
343 if ( (time() - filemtime($cache_file)) > ($this->cache_timeout*3600) &&
344 !(file_exists($cache_file . ".updating") && (time() - filemtime($cache_file . ".updating") < 60)) )
346 touch($cache_file . ".updating"); // Show that we in the process of updating the cache
350 $result_cache = unserialize(file_get_contents($cache_file));
352 $this->col_info = $result_cache['col_info'];
353 $this->last_result = $result_cache['last_result'];
354 $this->num_rows = $result_cache['num_rows'];
356 $this->from_disk_cache = true;
358 // If debug ALL queries
359 $this->trace || $this->debug_all ? $this->debug() : null ;
361 return $result_cache['return_value'];
367 /**********************************************************************
368 * Dumps the contents of any input variable to screen in a nicely
369 * formatted and easy to understand way - any type: Object, Var or Array
372 function vardump($mixed='')
375 // Start outup buffering
378 echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";
379 echo "<pre><font face=arial>";
381 if ( ! $this->vardump_called )
383 echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";
386 $var_type = gettype ($mixed);
387 print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));
388 echo "\n\n<b>Type:</b> " . ucfirst($var_type) . "\n";
389 echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query?$this->last_query:"NULL")."\n";
390 echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";
391 echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";
392 echo "</font></pre></font></blockquote></td></tr></table>".$this->donation();
393 echo "\n<hr size=1 noshade color=dddddd>";
395 // Stop output buffering and capture debug HTML
396 $html = ob_get_contents();
399 // Only echo output if it is turned on
400 if ( $this->debug_echo_is_on )
405 $this->vardump_called = true;
411 /**********************************************************************
412 * Alias for the above function
415 function dumpvar($mixed)
417 $this->vardump($mixed);
420 /**********************************************************************
421 * Displays the last query string that was sent to the database & a
422 * table listing results (if there were any).
423 * (abstracted into a seperate file to save server overhead).
426 function debug($print_to_screen=true)
429 // Start outup buffering
434 // Only show ezSQL credits once..
435 if ( ! $this->debug_called )
437 echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";
440 if ( $this->last_error )
442 echo "<font face=arial size=2 color=000099><b>Last Error --</b> [<font color=000000><b>$this->last_error</b></font>]<p>";
445 if ( $this->from_disk_cache )
447 echo "<font face=arial size=2 color=000099><b>Results retrieved from disk cache</b></font><p>";
450 echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";
451 echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
453 echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
456 if ( $this->col_info )
459 // =====================================================
462 echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
463 echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
466 for ( $i=0; $i < count($this->col_info); $i++ )
468 echo "<td nowrap align=left valign=top><font size=1 color=555599 face=arial>{$this->col_info[$i]->type} {$this->col_info[$i]->max_length}</font><br><span style='font-family: arial; font-size: 10pt; font-weight: bold;'>{$this->col_info[$i]->name}</span></td>";
473 // ======================================================
474 // print main results
476 if ( $this->last_result )
480 foreach ( $this->get_results(null,ARRAY_N) as $one_row )
483 echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
485 foreach ( $one_row as $item )
487 echo "<td nowrap><font face=arial size=2>$item</font></td>";
496 echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";
504 echo "<font face=arial size=2>No Results</font>";
507 echo "</blockquote></blockquote>".$this->donation()."<hr noshade color=dddddd size=1>";
509 // Stop output buffering and capture debug HTML
510 $html = ob_get_contents();
513 // Only echo output if it is turned on
514 if ( $this->debug_echo_is_on && $print_to_screen)
519 $this->debug_called = true;
525 /**********************************************************************
526 * Naughty little function to ask for some remuniration!
531 return "<font size=1 face=arial color=000000>If ezSQL has helped <a href=\"https://www.paypal.com/xclick/business=justin%40justinvincent.com&item_name=ezSQL&no_note=1&tax=0\" style=\"color: 0000CC;\">make a donation!?</a> <!--[ go on! you know you want to! ]--></font>";
534 /**********************************************************************
535 * Timer related functions
538 function timer_get_cur()
540 list($usec, $sec) = explode(" ",microtime());
541 return ((float)$usec + (float)$sec);
544 function timer_start($timer_name)
546 $this->timers[$timer_name] = $this->timer_get_cur();
549 function timer_elapsed($timer_name)
551 return round($this->timer_get_cur() - $this->timers[$timer_name],2);
554 function timer_update_global($timer_name)
556 if ( $this->do_profile )
558 $this->profile_times[] = array
560 'query' => $this->last_query,
561 'time' => $this->timer_elapsed($timer_name)
565 $this->total_query_time += $this->timer_elapsed($timer_name);
568 /**********************************************************************
569 * Creates a SET nvp sql string from an associative array (and escapes all values)
573 * $db_data = array('login'=>'jv','email'=>'jv@vip.ie', 'user_id' => 1, 'created' => 'NOW()');
575 * $db->query("INSERT INTO users SET ".$db->get_set($db_data));
579 * $db->query("UPDATE users SET ".$db->get_set($db_data)." WHERE user_id = 1");
583 * login = 'jv', email = 'jv@vip.ie', user_id = 1, created = NOW()
586 function get_set($params)
588 if( !is_array( $params ) )
590 $this->register_error( 'get_set() parameter invalid. Expected array in '.__FILE__.' on line '.__LINE__);
594 foreach ( $params as $field => $val )
596 if ( $val === 'true' || $val === true )
598 if ( $val === 'false' || $val === false )
604 $sql[] = "$field = $val";
607 $sql[] = "$field = '".$this->escape( $val )."'";
611 return implode( ', ' , $sql );