]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/class-mysql.php
Added missing function from previous ezSQL lib
[Github/YOURLS.git] / includes / class-mysql.php
1 <?php\r
2 \r
3 /**********************************************************************\r
4 *  Author: Justin Vincent (jv@vip.ie)\r
5 *  Web...: http://justinvincent.com\r
6 *  Name..: ezSQL\r
7 *  Desc..: ezSQL Core module - database abstraction library to make\r
8 *          it very easy to deal with databases. ezSQLcore can not be used by \r
9 *          itself (it is designed for use by database specific modules).\r
10 *\r
11 */\r
12 \r
13 /**********************************************************************\r
14 *  ezSQL Constants\r
15 */\r
16 \r
17 define('EZSQL_VERSION','2.17');\r
18 define('OBJECT','OBJECT',true);\r
19 define('ARRAY_A','ARRAY_A',true);\r
20 define('ARRAY_N','ARRAY_N',true);\r
21 \r
22 /**********************************************************************\r
23 *  Core class containg common functions to manipulate query result\r
24 *  sets once returned\r
25 */\r
26 \r
27 class ezSQLcore\r
28 {\r
29 \r
30         var $trace            = false;  // same as $debug_all\r
31         var $debug_all        = false;  // same as $trace\r
32         var $debug_called     = false;\r
33         var $vardump_called   = false;\r
34         var $show_errors      = true;\r
35         var $num_queries      = 0;\r
36         var $last_query       = null;\r
37         var $last_error       = null;\r
38         var $col_info         = null;\r
39         var $captured_errors  = array();\r
40         var $cache_dir        = false;\r
41         var $cache_queries    = false;\r
42         var $cache_inserts    = false;\r
43         var $use_disk_cache   = false;\r
44         var $cache_timeout    = 24; // hours\r
45         var $timers           = array();\r
46         var $total_query_time = 0;\r
47         var $db_connect_time  = 0;\r
48         var $trace_log        = array();\r
49         var $use_trace_log    = false;\r
50         var $sql_log_file     = false;\r
51         var $do_profile       = false;\r
52         var $profile_times    = array();\r
53         var $all_queries      = '';\r
54 \r
55         // == TJH == default now needed for echo of debug function\r
56         var $debug_echo_is_on = true;\r
57 \r
58         /**********************************************************************\r
59         *  Constructor\r
60         */\r
61 \r
62         function ezSQLcore()\r
63         {\r
64         }\r
65 \r
66         /**********************************************************************\r
67         *  Print SQL/DB error - over-ridden by specific DB class\r
68         */\r
69 \r
70         function register_error($err_str)\r
71         {\r
72                 // Keep track of last error\r
73                 $this->last_error = $err_str;\r
74 \r
75                 // Capture all errors to an error array no matter what happens\r
76                 $this->captured_errors[] = array\r
77                 (\r
78                         'error_str' => $err_str,\r
79                         'query'     => $this->last_query\r
80                 );\r
81         }\r
82 \r
83         /**********************************************************************\r
84         *  Turn error handling on or off..\r
85         */\r
86 \r
87         function show_errors()\r
88         {\r
89                 $this->show_errors = true;\r
90         }\r
91 \r
92         function hide_errors()\r
93         {\r
94                 $this->show_errors = false;\r
95         }\r
96 \r
97         /**********************************************************************\r
98         *  Kill cached query results\r
99         */\r
100 \r
101         function flush()\r
102         {\r
103                 // Get rid of these\r
104                 $this->last_result = null;\r
105                 $this->col_info = null;\r
106                 $this->last_query = null;\r
107                 $this->from_disk_cache = false;\r
108         }\r
109 \r
110         /**********************************************************************\r
111         *  Get one variable from the DB - see docs for more detail\r
112         */\r
113 \r
114         function get_var($query=null,$x=0,$y=0)\r
115         {\r
116 \r
117                 // Log how the function was called\r
118                 $this->func_call = "\$db->get_var(\"$query\",$x,$y)";\r
119 \r
120                 // If there is a query then perform it if not then use cached results..\r
121                 if ( $query )\r
122                 {\r
123                         $this->query($query);\r
124                 }\r
125 \r
126                 // Extract var out of cached results based x,y vals\r
127                 if ( $this->last_result[$y] )\r
128                 {\r
129                         $values = array_values(get_object_vars($this->last_result[$y]));\r
130                 }\r
131 \r
132                 // If there is a value return it else return null\r
133                 return (isset($values[$x]) && $values[$x]!=='')?$values[$x]:null;\r
134         }\r
135 \r
136         /**********************************************************************\r
137         *  Get one row from the DB - see docs for more detail\r
138         */\r
139 \r
140         function get_row($query=null,$output=OBJECT,$y=0)\r
141         {\r
142 \r
143                 // Log how the function was called\r
144                 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";\r
145 \r
146                 // If there is a query then perform it if not then use cached results..\r
147                 if ( $query )\r
148                 {\r
149                         $this->query($query);\r
150                 }\r
151 \r
152                 // If the output is an object then return object using the row offset..\r
153                 if ( $output == OBJECT )\r
154                 {\r
155                         return $this->last_result[$y]?$this->last_result[$y]:null;\r
156                 }\r
157                 // If the output is an associative array then return row as such..\r
158                 elseif ( $output == ARRAY_A )\r
159                 {\r
160                         return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null;\r
161                 }\r
162                 // If the output is an numerical array then return row as such..\r
163                 elseif ( $output == ARRAY_N )\r
164                 {\r
165                         return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null;\r
166                 }\r
167                 // If invalid output type was specified..\r
168                 else\r
169                 {\r
170                         $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;\r
171                 }\r
172 \r
173         }\r
174 \r
175         /**********************************************************************\r
176         *  Function to get 1 column from the cached result set based in X index\r
177         *  see docs for usage and info\r
178         */\r
179 \r
180         function get_col($query=null,$x=0)\r
181         {\r
182 \r
183                 $new_array = array();\r
184 \r
185                 // If there is a query then perform it if not then use cached results..\r
186                 if ( $query )\r
187                 {\r
188                         $this->query($query);\r
189                 }\r
190 \r
191                 // Extract the column values\r
192                 for ( $i=0; $i < count($this->last_result); $i++ )\r
193                 {\r
194                         $new_array[$i] = $this->get_var(null,$x,$i);\r
195                 }\r
196 \r
197                 return $new_array;\r
198         }\r
199 \r
200 \r
201         /**********************************************************************\r
202         *  Return the the query as a result set - see docs for more details\r
203         */\r
204 \r
205         function get_results($query=null, $output = OBJECT)\r
206         {\r
207 \r
208                 // Log how the function was called\r
209                 $this->func_call = "\$db->get_results(\"$query\", $output)";\r
210 \r
211                 // If there is a query then perform it if not then use cached results..\r
212                 if ( $query )\r
213                 {\r
214                         $this->query($query);\r
215                 }\r
216 \r
217                 // Send back array of objects. Each row is an object\r
218                 if ( $output == OBJECT )\r
219                 {\r
220                         return $this->last_result;\r
221                 }\r
222                 elseif ( $output == ARRAY_A || $output == ARRAY_N )\r
223                 {\r
224                         if ( $this->last_result )\r
225                         {\r
226                                 $i=0;\r
227                                 foreach( $this->last_result as $row )\r
228                                 {\r
229 \r
230                                         $new_array[$i] = get_object_vars($row);\r
231 \r
232                                         if ( $output == ARRAY_N )\r
233                                         {\r
234                                                 $new_array[$i] = array_values($new_array[$i]);\r
235                                         }\r
236 \r
237                                         $i++;\r
238                                 }\r
239 \r
240                                 return $new_array;\r
241                         }\r
242                         else\r
243                         {\r
244                                 return null;\r
245                         }\r
246                 }\r
247         }\r
248 \r
249 \r
250         /**********************************************************************\r
251         *  Function to get column meta data info pertaining to the last query\r
252         * see docs for more info and usage\r
253         */\r
254 \r
255         function get_col_info($info_type="name",$col_offset=-1)\r
256         {\r
257 \r
258                 if ( $this->col_info )\r
259                 {\r
260                         if ( $col_offset == -1 )\r
261                         {\r
262                                 $i=0;\r
263                                 foreach($this->col_info as $col )\r
264                                 {\r
265                                         $new_array[$i] = $col->{$info_type};\r
266                                         $i++;\r
267                                 }\r
268                                 return $new_array;\r
269                         }\r
270                         else\r
271                         {\r
272                                 return $this->col_info[$col_offset]->{$info_type};\r
273                         }\r
274 \r
275                 }\r
276 \r
277         }\r
278 \r
279         /**********************************************************************\r
280         *  store_cache\r
281         */\r
282 \r
283         function store_cache($query,$is_insert)\r
284         {\r
285 \r
286                 // The would be cache file for this query\r
287                 $cache_file = $this->cache_dir.'/'.md5($query);\r
288 \r
289                 // disk caching of queries\r
290                 if ( $this->use_disk_cache && ( $this->cache_queries && ! $is_insert ) || ( $this->cache_inserts && $is_insert ))\r
291                 {\r
292                         if ( ! is_dir($this->cache_dir) )\r
293                         {\r
294                                 $this->register_error("Could not open cache dir: $this->cache_dir");\r
295                                 $this->show_errors ? trigger_error("Could not open cache dir: $this->cache_dir",E_USER_WARNING) : null;\r
296                         }\r
297                         else\r
298                         {\r
299                                 // Cache all result values\r
300                                 $result_cache = array\r
301                                 (\r
302                                         'col_info' => $this->col_info,\r
303                                         'last_result' => $this->last_result,\r
304                                         'num_rows' => $this->num_rows,\r
305                                         'return_value' => $this->num_rows,\r
306                                 );\r
307                                 file_put_contents($cache_file, serialize($result_cache));\r
308                                 if( file_exists($cache_file . ".updating") )\r
309                                         unlink($cache_file . ".updating");\r
310                         }\r
311                 }\r
312 \r
313         }\r
314 \r
315         /**********************************************************************\r
316         *  get_cache\r
317         */\r
318 \r
319         function get_cache($query)\r
320         {\r
321 \r
322                 // The would be cache file for this query\r
323                 $cache_file = $this->cache_dir.'/'.md5($query);\r
324 \r
325                 // Try to get previously cached version\r
326                 if ( $this->use_disk_cache && file_exists($cache_file) )\r
327                 {\r
328                         // Only use this cache file if less than 'cache_timeout' (hours)\r
329                         if ( (time() - filemtime($cache_file)) > ($this->cache_timeout*3600) && \r
330                                 !(file_exists($cache_file . ".updating") && (time() - filemtime($cache_file . ".updating") < 60)) ) \r
331                         {\r
332                                 touch($cache_file . ".updating"); // Show that we in the process of updating the cache\r
333                         }\r
334                         else\r
335                         {\r
336                                 $result_cache = unserialize(file_get_contents($cache_file));\r
337 \r
338                                 $this->col_info = $result_cache['col_info'];\r
339                                 $this->last_result = $result_cache['last_result'];\r
340                                 $this->num_rows = $result_cache['num_rows'];\r
341 \r
342                                 $this->from_disk_cache = true;\r
343 \r
344                                 // If debug ALL queries\r
345                                 $this->trace || $this->debug_all ? $this->debug() : null ;\r
346 \r
347                                 return $result_cache['return_value'];\r
348                         }\r
349                 }\r
350 \r
351         }\r
352 \r
353         /**********************************************************************\r
354         *  Dumps the contents of any input variable to screen in a nicely\r
355         *  formatted and easy to understand way - any type: Object, Var or Array\r
356         */\r
357 \r
358         function vardump($mixed='')\r
359         {\r
360 \r
361                 // Start outup buffering\r
362                 ob_start();\r
363 \r
364                 echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";\r
365                 echo "<pre><font face=arial>";\r
366 \r
367                 if ( ! $this->vardump_called )\r
368                 {\r
369                         echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";\r
370                 }\r
371 \r
372                 $var_type = gettype ($mixed);\r
373                 print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));\r
374                 echo "\n\n<b>Type:</b> " . ucfirst($var_type) . "\n";\r
375                 echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query?$this->last_query:"NULL")."\n";\r
376                 echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";\r
377                 echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";\r
378                 echo "</font></pre></font></blockquote></td></tr></table>".$this->donation();\r
379                 echo "\n<hr size=1 noshade color=dddddd>";\r
380 \r
381                 // Stop output buffering and capture debug HTML\r
382                 $html = ob_get_contents();\r
383                 ob_end_clean();\r
384 \r
385                 // Only echo output if it is turned on\r
386                 if ( $this->debug_echo_is_on )\r
387                 {\r
388                         echo $html;\r
389                 }\r
390 \r
391                 $this->vardump_called = true;\r
392 \r
393                 return $html;\r
394 \r
395         }\r
396 \r
397         /**********************************************************************\r
398         *  Alias for the above function\r
399         */\r
400 \r
401         function dumpvar($mixed)\r
402         {\r
403                 $this->vardump($mixed);\r
404         }\r
405 \r
406         /**********************************************************************\r
407         *  Displays the last query string that was sent to the database & a\r
408         * table listing results (if there were any).\r
409         * (abstracted into a seperate file to save server overhead).\r
410         */\r
411 \r
412         function debug($print_to_screen=true)\r
413         {\r
414 \r
415                 // Start outup buffering\r
416                 ob_start();\r
417 \r
418                 echo "<blockquote>";\r
419 \r
420                 // Only show ezSQL credits once..\r
421                 if ( ! $this->debug_called )\r
422                 {\r
423                         echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";\r
424                 }\r
425 \r
426                 if ( $this->last_error )\r
427                 {\r
428                         echo "<font face=arial size=2 color=000099><b>Last Error --</b> [<font color=000000><b>$this->last_error</b></font>]<p>";\r
429                 }\r
430 \r
431                 if ( $this->from_disk_cache )\r
432                 {\r
433                         echo "<font face=arial size=2 color=000099><b>Results retrieved from disk cache</b></font><p>";\r
434                 }\r
435 \r
436                 echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";\r
437                 echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";\r
438 \r
439                         echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";\r
440                         echo "<blockquote>";\r
441 \r
442                 if ( $this->col_info )\r
443                 {\r
444 \r
445                         // =====================================================\r
446                         // Results top rows\r
447 \r
448                         echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";\r
449                         echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";\r
450 \r
451 \r
452                         for ( $i=0; $i < count($this->col_info); $i++ )\r
453                         {\r
454                                 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>";\r
455                         }\r
456 \r
457                         echo "</tr>";\r
458 \r
459                         // ======================================================\r
460                         // print main results\r
461 \r
462                 if ( $this->last_result )\r
463                 {\r
464 \r
465                         $i=0;\r
466                         foreach ( $this->get_results(null,ARRAY_N) as $one_row )\r
467                         {\r
468                                 $i++;\r
469                                 echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";\r
470 \r
471                                 foreach ( $one_row as $item )\r
472                                 {\r
473                                         echo "<td nowrap><font face=arial size=2>$item</font></td>";\r
474                                 }\r
475 \r
476                                 echo "</tr>";\r
477                         }\r
478 \r
479                 } // if last result\r
480                 else\r
481                 {\r
482                         echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";\r
483                 }\r
484 \r
485                 echo "</table>";\r
486 \r
487                 } // if col_info\r
488                 else\r
489                 {\r
490                         echo "<font face=arial size=2>No Results</font>";\r
491                 }\r
492 \r
493                 echo "</blockquote></blockquote>".$this->donation()."<hr noshade color=dddddd size=1>";\r
494 \r
495                 // Stop output buffering and capture debug HTML\r
496                 $html = ob_get_contents();\r
497                 ob_end_clean();\r
498 \r
499                 // Only echo output if it is turned on\r
500                 if ( $this->debug_echo_is_on && $print_to_screen)\r
501                 {\r
502                         echo $html;\r
503                 }\r
504 \r
505                 $this->debug_called = true;\r
506 \r
507                 return $html;\r
508 \r
509         }\r
510 \r
511         /**********************************************************************\r
512         *  Naughty little function to ask for some remuniration!\r
513         */\r
514 \r
515         function donation()\r
516         {\r
517                 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> &nbsp;&nbsp;<!--[ go on! you know you want to! ]--></font>";\r
518         }\r
519 \r
520         /**********************************************************************\r
521         *  Timer related functions\r
522         */\r
523 \r
524         function timer_get_cur()\r
525         {\r
526                 list($usec, $sec) = explode(" ",microtime());\r
527                 return ((float)$usec + (float)$sec);\r
528         }\r
529 \r
530         function timer_start($timer_name)\r
531         {\r
532                 $this->timers[$timer_name] = $this->timer_get_cur();\r
533         }\r
534 \r
535         function timer_elapsed($timer_name)\r
536         {\r
537                 return round($this->timer_get_cur() - $this->timers[$timer_name],2);\r
538         }\r
539 \r
540         function timer_update_global($timer_name)\r
541         {\r
542                 if ( $this->do_profile )\r
543                 {\r
544                         $this->profile_times[] = array\r
545                         (\r
546                                 'query' => $this->last_query,\r
547                                 'time' => $this->timer_elapsed($timer_name)\r
548                         );\r
549                 }\r
550                 \r
551                 $this->total_query_time += $this->timer_elapsed($timer_name);\r
552         }\r
553 \r
554         /**********************************************************************\r
555         * Creates a SET nvp sql string from an associative array (and escapes all values)\r
556         *\r
557         *  Usage:\r
558         *\r
559         *     $db_data = array('login'=>'jv','email'=>'jv@vip.ie', 'user_id' => 1, 'created' => 'NOW()');\r
560         *\r
561         *     $db->query("INSERT INTO users SET ".$db->get_set($db_data));\r
562         *\r
563         *     ...OR...\r
564         *\r
565         *     $db->query("UPDATE users SET ".$db->get_set($db_data)." WHERE user_id = 1");\r
566         *\r
567         * Output:\r
568         *\r
569         *     login = 'jv', email = 'jv@vip.ie', user_id = 1, created = NOW()\r
570         */\r
571 \r
572         function get_set($parms)\r
573         {               \r
574                 $sql = '';\r
575                 foreach ( $parms as $field => $val )\r
576                 {\r
577                         if ( $val === 'true' ) $val = 1;\r
578                         if ( $val === 'false' ) $val = 0;\r
579                 \r
580                         if ( $val == 'NOW()' )\r
581                         {\r
582                                 $sql .= "$field = ".$this->escape($val).", ";\r
583                         }\r
584                         else\r
585                         {\r
586                                 $sql .= "$field = '".$this->escape($val)."', ";\r
587                         }\r
588                 }\r
589         \r
590                 return substr($sql,0,-2);\r
591         }\r
592 \r
593 }\r
594 \r
595 \r
596 /**********************************************************************\r
597 *  Author: Justin Vincent (jv@jvmultimedia.com)\r
598 *  Web...: http://twitter.com/justinvincent\r
599 *  Name..: ezSQL_mysql\r
600 *  Desc..: mySQL component (part of ezSQL databse abstraction library)\r
601 *\r
602 */\r
603 \r
604 /**********************************************************************\r
605 *  ezSQL error strings - mySQL\r
606 */\r
607 \r
608 $ezsql_mysql_str = array\r
609 (\r
610         1 => 'Require $dbuser and $dbpassword to connect to a database server',\r
611         2 => 'Error establishing mySQL database connection. Correct user/password? Correct hostname? Database server running?',\r
612         3 => 'Require $dbname to select a database',\r
613         4 => 'mySQL database connection is not active',\r
614         5 => 'Unexpected error while trying to select database'\r
615 );\r
616 \r
617 /**********************************************************************\r
618 *  ezSQL Database specific class - mySQL\r
619 */\r
620 \r
621 if ( ! function_exists ('mysql_connect') ) die('<b>Fatal Error:</b> ezSQL_mysql requires mySQL Lib to be compiled and or linked in to the PHP engine');\r
622 if ( ! class_exists ('ezSQLcore') ) die('<b>Fatal Error:</b> ezSQL_mysql requires ezSQLcore (ez_sql_core.php) to be included/loaded before it can be used');\r
623 \r
624 class ezSQL_mysql extends ezSQLcore\r
625 {\r
626 \r
627         var $dbuser = false;\r
628         var $dbpassword = false;\r
629         var $dbname = false;\r
630         var $dbhost = false;\r
631         var $encoding = false;\r
632 \r
633         /**********************************************************************\r
634         *  Constructor - allow the user to perform a qucik connect at the\r
635         *  same time as initialising the ezSQL_mysql class\r
636         */\r
637 \r
638         function ezSQL_mysql($dbuser='', $dbpassword='', $dbname='', $dbhost='localhost', $encoding='')\r
639         {\r
640                 $this->dbuser = $dbuser;\r
641                 $this->dbpassword = $dbpassword;\r
642                 $this->dbname = $dbname;\r
643                 $this->dbhost = $dbhost;\r
644                 $this->encoding = $encoding;\r
645         }\r
646 \r
647         /**********************************************************************\r
648         *  Short hand way to connect to mySQL database server\r
649         *  and select a mySQL database at the same time\r
650         */\r
651 \r
652         function quick_connect($dbuser='', $dbpassword='', $dbname='', $dbhost='localhost', $encoding='')\r
653         {\r
654                 $return_val = false;\r
655                 if ( ! $this->connect($dbuser, $dbpassword, $dbhost,true) ) ;\r
656                 else if ( ! $this->select($dbname,$encoding) ) ;\r
657                 else $return_val = true;\r
658                 return $return_val;\r
659         }\r
660 \r
661         /**********************************************************************\r
662         *  Try to connect to mySQL database server\r
663         */\r
664 \r
665         function connect($dbuser='', $dbpassword='', $dbhost='localhost')\r
666         {\r
667                 global $ezsql_mysql_str; $return_val = false;\r
668                 \r
669                 // Keep track of how long the DB takes to connect\r
670                 $this->timer_start('db_connect_time');\r
671 \r
672                 // Must have a user and a password\r
673                 if ( ! $dbuser )\r
674                 {\r
675                         $this->register_error($ezsql_mysql_str[1].' in '.__FILE__.' on line '.__LINE__);\r
676                         $this->show_errors ? trigger_error($ezsql_mysql_str[1],E_USER_WARNING) : null;\r
677                 }\r
678                 // Try to establish the server database handle\r
679                 else if ( ! $this->dbh = @mysql_connect($dbhost,$dbuser,$dbpassword,true,131074) )\r
680                 {\r
681                         $this->register_error($ezsql_mysql_str[2].' in '.__FILE__.' on line '.__LINE__);\r
682                         $this->show_errors ? trigger_error($ezsql_mysql_str[2],E_USER_WARNING) : null;\r
683                 }\r
684                 else\r
685                 {\r
686                         $this->dbuser = $dbuser;\r
687                         $this->dbpassword = $dbpassword;\r
688                         $this->dbhost = $dbhost;\r
689                         $return_val = true;\r
690                 }\r
691 \r
692                 return $return_val;\r
693         }\r
694 \r
695         /**********************************************************************\r
696         *  Try to select a mySQL database\r
697         */\r
698 \r
699         function select($dbname='', $encoding='')\r
700         {\r
701                 global $ezsql_mysql_str; $return_val = false;\r
702 \r
703                 // Must have a database name\r
704                 if ( ! $dbname )\r
705                 {\r
706                         $this->register_error($ezsql_mysql_str[3].' in '.__FILE__.' on line '.__LINE__);\r
707                         $this->show_errors ? trigger_error($ezsql_mysql_str[3],E_USER_WARNING) : null;\r
708                 }\r
709 \r
710                 // Must have an active database connection\r
711                 else if ( ! $this->dbh )\r
712                 {\r
713                         $this->register_error($ezsql_mysql_str[4].' in '.__FILE__.' on line '.__LINE__);\r
714                         $this->show_errors ? trigger_error($ezsql_mysql_str[4],E_USER_WARNING) : null;\r
715                 }\r
716 \r
717                 // Try to connect to the database\r
718                 else if ( !@mysql_select_db($dbname,$this->dbh) )\r
719                 {\r
720                         // Try to get error supplied by mysql if not use our own\r
721                         if ( !$str = @mysql_error($this->dbh))\r
722                                   $str = $ezsql_mysql_str[5];\r
723 \r
724                         $this->register_error($str.' in '.__FILE__.' on line '.__LINE__);\r
725                         $this->show_errors ? trigger_error($str,E_USER_WARNING) : null;\r
726                 }\r
727                 else\r
728                 {\r
729                         $this->dbname = $dbname;\r
730                         if($encoding!='')\r
731                         {\r
732                                 $encoding = strtolower(str_replace("-","",$encoding));\r
733                                 $charsets = array();\r
734                                 $result = mysql_query("SHOW CHARACTER SET");\r
735                                 while($row = mysql_fetch_array($result,MYSQL_ASSOC))\r
736                                 {\r
737                                         $charsets[] = $row["Charset"];\r
738                                 }\r
739                                 if(in_array($encoding,$charsets)){\r
740                                         mysql_query("SET NAMES '".$encoding."'");                                               \r
741                                 }\r
742                         }\r
743                         \r
744                         $return_val = true;\r
745                 }\r
746 \r
747                 return $return_val;\r
748         }\r
749 \r
750         /**********************************************************************\r
751         *  Format a mySQL string correctly for safe mySQL insert\r
752         *  (no mater if magic quotes are on or not)\r
753         */\r
754 \r
755         function escape($str)\r
756         {\r
757                 // If there is no existing database connection then try to connect\r
758                 if ( ! isset($this->dbh) || ! $this->dbh )\r
759                 {\r
760                         $this->connect($this->dbuser, $this->dbpassword, $this->dbhost);\r
761                         $this->select($this->dbname, $this->encoding);\r
762                 }\r
763 \r
764                 return mysql_real_escape_string(stripslashes($str));\r
765         }\r
766 \r
767         /**********************************************************************\r
768         *  Return mySQL specific system date syntax\r
769         *  i.e. Oracle: SYSDATE Mysql: NOW()\r
770         */\r
771 \r
772         function sysdate()\r
773         {\r
774                 return 'NOW()';\r
775         }\r
776 \r
777         /**********************************************************************\r
778         *  Perform mySQL query and try to detirmin result value\r
779         */\r
780 \r
781         function query($query)\r
782         {\r
783 \r
784                 // This keeps the connection alive for very long running scripts\r
785                 if ( $this->num_queries >= 500 )\r
786                 {\r
787                         $this->disconnect();\r
788                         $this->quick_connect($this->dbuser,$this->dbpassword,$this->dbname,$this->dbhost,$this->encoding);\r
789                 }\r
790 \r
791                 // Initialise return\r
792                 $return_val = 0;\r
793 \r
794                 // Flush cached values..\r
795                 $this->flush();\r
796 \r
797                 // For reg expressions\r
798                 $query = trim($query);\r
799 \r
800                 // Log how the function was called\r
801                 $this->func_call = "\$db->query(\"$query\")";\r
802 \r
803                 // Keep track of the last query for debug..\r
804                 $this->last_query = $query;\r
805 \r
806                 // Count how many queries there have been\r
807                 $this->num_queries++;\r
808                 \r
809                 // Keep history of all queries\r
810                 $this->all_queries .= $query.'<br />';\r
811                 \r
812                 // Start timer\r
813                 $this->timer_start($this->num_queries);\r
814 \r
815                 // Use core file cache function\r
816                 if ( $cache = $this->get_cache($query) )\r
817                 {\r
818                         // Keep tack of how long all queries have taken\r
819                         $this->timer_update_global($this->num_queries);\r
820 \r
821                         // Trace all queries\r
822                         if ( $this->use_trace_log )\r
823                         {\r
824                                 $this->trace_log[] = $this->debug(false);\r
825                         }\r
826                         \r
827                         return $cache;\r
828                 }\r
829 \r
830                 // If there is no existing database connection then try to connect\r
831                 if ( ! isset($this->dbh) || ! $this->dbh )\r
832                 {\r
833                         $this->connect($this->dbuser, $this->dbpassword, $this->dbhost);\r
834                         $this->select($this->dbname,$this->encoding);\r
835                 }\r
836 \r
837                 // Perform the query via std mysql_query function..\r
838                 $this->result = @mysql_query($query,$this->dbh);\r
839 \r
840                 // If there is an error then take note of it..\r
841                 if ( $str = @mysql_error($this->dbh) )\r
842                 {\r
843                         $is_insert = true;\r
844                         $this->register_error($str);\r
845                         $this->show_errors ? trigger_error($str,E_USER_WARNING) : null;\r
846                         return false;\r
847                 }\r
848 \r
849                 // Query was an insert, delete, update, replace\r
850                 $is_insert = false;\r
851                 if ( preg_match("/^(insert|delete|update|replace|truncate|drop|create|alter)\s+/i",$query) )\r
852                 {\r
853                         $this->rows_affected = @mysql_affected_rows($this->dbh);\r
854 \r
855                         // Take note of the insert_id\r
856                         if ( preg_match("/^(insert|replace)\s+/i",$query) )\r
857                         {\r
858                                 $this->insert_id = @mysql_insert_id($this->dbh);\r
859                         }\r
860 \r
861                         // Return number fo rows affected\r
862                         $return_val = $this->rows_affected;\r
863                 }\r
864                 // Query was a select\r
865                 else\r
866                 {\r
867 \r
868                         // Take note of column info\r
869                         $i=0;\r
870                         while ($i < @mysql_num_fields($this->result))\r
871                         {\r
872                                 $this->col_info[$i] = @mysql_fetch_field($this->result);\r
873                                 $i++;\r
874                         }\r
875 \r
876                         // Store Query Results\r
877                         $num_rows=0;\r
878                         while ( $row = @mysql_fetch_object($this->result) )\r
879                         {\r
880                                 // Store relults as an objects within main array\r
881                                 $this->last_result[$num_rows] = $row;\r
882                                 $num_rows++;\r
883                         }\r
884 \r
885                         @mysql_free_result($this->result);\r
886 \r
887                         // Log number of rows the query returned\r
888                         $this->num_rows = $num_rows;\r
889 \r
890                         // Return number of rows selected\r
891                         $return_val = $this->num_rows;\r
892                 }\r
893 \r
894                 // disk caching of queries\r
895                 $this->store_cache($query,$is_insert);\r
896 \r
897                 // If debug ALL queries\r
898                 $this->trace || $this->debug_all ? $this->debug() : null ;\r
899 \r
900                 // Keep tack of how long all queries have taken\r
901                 $this->timer_update_global($this->num_queries);\r
902 \r
903                 // Trace all queries\r
904                 if ( $this->use_trace_log )\r
905                 {\r
906                         $this->trace_log[] = $this->debug(false);\r
907                 }\r
908 \r
909                 return $return_val;\r
910 \r
911         }\r
912         \r
913         /**********************************************************************\r
914         *  Close the active mySQL connection\r
915         */\r
916 \r
917         function disconnect()\r
918         {\r
919                 @mysql_close($this->dbh);       \r
920         }\r
921 \r
922         function mysql_version() {\r
923                 return  mysql_get_server_info( $this->dbh ) ;\r
924         }\r
925 }\r