PageRenderTime 27ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/php/db.class.php

https://github.com/jclay06/scms
PHP | 657 lines | 372 code | 156 blank | 129 comment | 76 complexity | a6d35ed49449bf001e9d031cd6ff819a MD5 | raw file
  1. <?php
  2. define('EZSQL_VERSION','2.03');
  3. define('OBJECT','OBJECT',true);
  4. define('ARRAY_A','ARRAY_A',true);
  5. define('ARRAY_N','ARRAY_N',true);
  6. define('EZSQL_CORE_ERROR','ezSQLcore can not be used by itself (it is designed for use by database specific modules).');
  7. $ezsql_mysql_str = array(
  8. 1 => 'Require $dbuser and $dbpassword to connect to a database server',
  9. 2 => 'Error establishing mySQL database connection. Correct user/password? Correct hostname? Database server running?',
  10. 3 => 'Require $dbname to select a database',
  11. 4 => 'mySQL database connection is not active',
  12. 5 => 'Unexpected error while trying to select database'
  13. );
  14. class scdb {
  15. public $trace = false; // same as $debug_all
  16. public $debug_all = false; // same as $trace
  17. public $debug_called = false;
  18. public $vardump_called = false;
  19. public $show_errors = true;
  20. public $num_queries = 0;
  21. public $last_query = null;
  22. public $last_error = null;
  23. public $col_info = null;
  24. public $captured_errors = array();
  25. public $cache_dir = false;
  26. public $cache_queries = false;
  27. public $cache_inserts = false;
  28. public $use_disk_cache = false;
  29. public $cache_timeout = 24; // hours
  30. public $dbuser = false;
  31. public $dbpassword = false;
  32. public $dbname = false;
  33. public $dbhost = false;
  34. // == TJH == default now needed for echo of debug function
  35. public $debug_echo_is_on = true;
  36. public $tables = array();
  37. public $table_prefix = '';
  38. /**********************************************************************
  39. * Constructor
  40. */
  41. public function scdb($dbuser='', $dbpassword='', $dbname='', $dbhost='localhost') {
  42. $this->__contruct($dbuser, $dbpassword, $dbname, $dbhost);
  43. }
  44. public function __construct($dbuser='', $dbpassword='', $dbname='', $dbhost='localhost') {
  45. $this->dbuser = $dbuser;
  46. $this->dbpassword = $dbpassword;
  47. $this->dbname = $dbname;
  48. $this->dbhost = $dbhost;
  49. }
  50. /**********************************************************************
  51. * Short hand way to connect to mySQL database server
  52. * and select a mySQL database at the same time
  53. */
  54. public function quick_connect($dbuser='', $dbpassword='', $dbname='', $dbhost='localhost') {
  55. $return_val = false;
  56. if ( ! $this->connect($dbuser, $dbpassword, $dbhost,true) ) ;
  57. elseif ( ! $this->select($dbname) ) ;
  58. else $return_val = true;
  59. return $return_val;
  60. }
  61. /**********************************************************************
  62. * Try to connect to mySQL database server
  63. */
  64. public function connect($dbuser='', $dbpassword='', $dbhost='localhost') {
  65. global $ezsql_mysql_str; $return_val = false;
  66. // Must have a user and a password
  67. if ( ! $dbuser ) {
  68. $this->register_error($ezsql_mysql_str[1].' in '.__FILE__.' on line '.__LINE__);
  69. $this->show_errors ? trigger_error($ezsql_mysql_str[1],E_USER_WARNING) : null;
  70. }
  71. // Try to establish the server database handle
  72. else if ( ! $this->dbh = @mysql_connect($dbhost,$dbuser,$dbpassword,true) ) {
  73. $this->register_error($ezsql_mysql_str[2].' in '.__FILE__.' on line '.__LINE__);
  74. $this->show_errors ? trigger_error($ezsql_mysql_str[2],E_USER_WARNING) : null;
  75. }
  76. else {
  77. $this->dbuser = $dbuser;
  78. $this->dbpassword = $dbpassword;
  79. $this->dbhost = $dbhost;
  80. $return_val = true;
  81. }
  82. return $return_val;
  83. }
  84. /**********************************************************************
  85. * Try to select a mySQL database
  86. */
  87. public function select($dbname='') {
  88. global $ezsql_mysql_str; $return_val = false;
  89. // Must have a database name
  90. if ( ! $dbname ) {
  91. $this->register_error($ezsql_mysql_str[3].' in '.__FILE__.' on line '.__LINE__);
  92. $this->show_errors ? trigger_error($ezsql_mysql_str[3],E_USER_WARNING) : null;
  93. }
  94. // Must have an active database connection
  95. else if ( ! $this->dbh ) {
  96. $this->register_error($ezsql_mysql_str[4].' in '.__FILE__.' on line '.__LINE__);
  97. $this->show_errors ? trigger_error($ezsql_mysql_str[4],E_USER_WARNING) : null;
  98. }
  99. // Try to connect to the database
  100. else if ( !@mysql_select_db($dbname,$this->dbh) ) {
  101. // Try to get error supplied by mysql if not use our own
  102. if ( !$str = @mysql_error($this->dbh))
  103. $str = $ezsql_mysql_str[5];
  104. $this->register_error($str.' in '.__FILE__.' on line '.__LINE__);
  105. $this->show_errors ? trigger_error($str,E_USER_WARNING) : null;
  106. }
  107. else {
  108. $this->dbname = $dbname;
  109. $return_val = true;
  110. }
  111. return $return_val;
  112. }
  113. public function set_table_prefix($prefix) {
  114. if( $prefix && strlen($prefix) > 0 ) {
  115. if ( preg_match('|[^a-z0-9_]|i', $prefix) )
  116. die('Invalid database prefix');
  117. }
  118. else $prefix = '';
  119. $old_prefix = $this->table_prefix;
  120. $this->table_prefix = $prefix;
  121. $this->set_tables($this->tables);
  122. return $old_prefix;
  123. }
  124. public function set_tables($tables) {
  125. if(!is_array($tables)) {
  126. die('$scdb->set_tables() should be called with an array of table names!');
  127. }
  128. $this->tables = $tables;
  129. foreach($this->tables as $table) {
  130. $this->$table = $this->table_prefix . $table;
  131. }
  132. }
  133. /**********************************************************************
  134. * Format a mySQL string correctly for safe mySQL insert
  135. * (no mater if magic quotes are on or not)
  136. */
  137. public function escape($str) {
  138. return mysql_escape_string(stripslashes($str));
  139. }
  140. /**********************************************************************
  141. * Return mySQL specific system date syntax
  142. * i.e. Oracle: SYSDATE Mysql: NOW()
  143. */
  144. public function sysdate() {
  145. return 'NOW()';
  146. }
  147. /**********************************************************************
  148. * Perform mySQL query and try to detirmin result value
  149. */
  150. public function query($query) {
  151. // Initialise return
  152. $return_val = 0;
  153. // Flush cached values..
  154. $this->flush();
  155. // For reg expressions
  156. $query = trim($query);
  157. // Log how the function was called
  158. $this->func_call = "\$db->query(\"$query\")";
  159. // Keep track of the last query for debug..
  160. $this->last_query = $query;
  161. // Count how many queries there have been
  162. $this->num_queries++;
  163. // Use core file cache function
  164. if ( $cache = $this->get_cache($query) ) {
  165. return $cache;
  166. }
  167. // If there is no existing database connection then try to connect
  168. if ( ! isset($this->dbh) || ! $this->dbh ) {
  169. $this->connect($this->dbuser, $this->dbpassword, $this->dbhost);
  170. $this->select($this->dbname);
  171. }
  172. // Perform the query via std mysql_query function..
  173. $this->result = @mysql_query($query,$this->dbh);
  174. // If there is an error then take note of it..
  175. if ( $str = @mysql_error($this->dbh) ) {
  176. $is_insert = true;
  177. $this->register_error($str);
  178. $this->show_errors ? trigger_error($str,E_USER_WARNING) : null;
  179. return false;
  180. }
  181. // Query was an insert, delete, update, replace
  182. $is_insert = false;
  183. if ( preg_match("/^(insert|delete|update|replace)\s+/i",$query) ) {
  184. $this->rows_affected = @mysql_affected_rows();
  185. // Take note of the insert_id
  186. if ( preg_match("/^(insert|replace)\s+/i",$query) ) {
  187. $this->insert_id = @mysql_insert_id($this->dbh);
  188. }
  189. // Return number of rows affected
  190. $return_val = $this->rows_affected;
  191. }
  192. // Query was a select
  193. else {
  194. // Take note of column info
  195. $i=0;
  196. while ($i < @mysql_num_fields($this->result)) {
  197. $this->col_info[$i] = @mysql_fetch_field($this->result);
  198. $i++;
  199. }
  200. // Store Query Results
  201. $num_rows=0;
  202. while ( $row = @mysql_fetch_object($this->result) ) {
  203. // Store relults as an objects within main array
  204. $this->last_result[$num_rows] = $row;
  205. $num_rows++;
  206. }
  207. @mysql_free_result($this->result);
  208. // Log number of rows the query returned
  209. $this->num_rows = $num_rows;
  210. // Return number of rows selected
  211. $return_val = $this->num_rows;
  212. }
  213. // disk caching of queries
  214. $this->store_cache($query,$is_insert);
  215. // If debug ALL queries
  216. $this->trace || $this->debug_all ? $this->debug() : null ;
  217. return $return_val;
  218. }
  219. /**********************************************************************
  220. * Print SQL/DB error - over-ridden by specific DB class
  221. */
  222. public function register_error($err_str) {
  223. // Keep track of last error
  224. $this->last_error = $err_str;
  225. // Capture all errors to an error array no matter what happens
  226. $this->captured_errors[] = array(
  227. 'error_str' => $err_str,
  228. 'query' => $this->last_query);
  229. }
  230. /**********************************************************************
  231. * Turn error handling on or off..
  232. */
  233. public function show_errors() {
  234. $this->show_errors = true;
  235. }
  236. public function hide_errors() {
  237. $this->show_errors = false;
  238. }
  239. /**********************************************************************
  240. * Kill cached query results
  241. */
  242. public function flush() {
  243. // Get rid of these
  244. $this->last_result = null;
  245. $this->col_info = null;
  246. $this->last_query = null;
  247. $this->from_disk_cache = false;
  248. }
  249. /**********************************************************************
  250. * Get one variable from the DB - see docs for more detail
  251. */
  252. public function get_var($query=null,$x=0,$y=0) {
  253. // Log how the function was called
  254. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  255. // If there is a query then perform it if not then use cached results..
  256. if ( $query ) {
  257. $this->query($query);
  258. }
  259. // Extract var out of cached results based x,y vals
  260. if ( $this->last_result[$y] ) {
  261. $values = array_values(get_object_vars($this->last_result[$y]));
  262. }
  263. // If there is a value return it else return null
  264. return (isset($values[$x]) && $values[$x]!=='')?$values[$x]:null;
  265. }
  266. /**********************************************************************
  267. * Get one row from the DB - see docs for more detail
  268. */
  269. public function get_row($query=null,$output=OBJECT,$y=0) {
  270. // Log how the function was called
  271. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  272. // If there is a query then perform it if not then use cached results..
  273. if ( $query ) {
  274. $this->query($query);
  275. }
  276. // If the output is an object then return object using the row offset..
  277. if ( $output == OBJECT ) {
  278. return $this->last_result[$y]?$this->last_result[$y]:null;
  279. }
  280. // If the output is an associative array then return row as such..
  281. elseif ( $output == ARRAY_A ) {
  282. return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null;
  283. }
  284. // If the output is an numerical array then return row as such..
  285. elseif ( $output == ARRAY_N ) {
  286. return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null;
  287. }
  288. // If invalid output type was specified..
  289. else {
  290. $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
  291. }
  292. }
  293. /**********************************************************************
  294. * Function to get 1 column from the cached result set based in X index
  295. * see docs for usage and info
  296. */
  297. public function get_col($query=null,$x=0) {
  298. // If there is a query then perform it if not then use cached results..
  299. if ( $query ) {
  300. $this->query($query);
  301. }
  302. // Extract the column values
  303. for ( $i=0; $i < count($this->last_result); $i++ ) {
  304. $new_array[$i] = $this->get_var(null,$x,$i);
  305. }
  306. return $new_array;
  307. }
  308. /**********************************************************************
  309. * Return the the query as a result set - see docs for more details
  310. */
  311. public function get_results($query=null, $output = OBJECT) {
  312. // Log how the function was called
  313. $this->func_call = "\$db->get_results(\"$query\", $output)";
  314. // If there is a query then perform it if not then use cached results..
  315. if ( $query ) {
  316. $this->query($query);
  317. }
  318. // Send back array of objects. Each row is an object
  319. if ( $output == OBJECT ) {
  320. return $this->last_result;
  321. }
  322. elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
  323. if ( $this->last_result ) {
  324. $i=0;
  325. foreach( $this->last_result as $row ) {
  326. $new_array[$i] = get_object_vars($row);
  327. if ( $output == ARRAY_N ) {
  328. $new_array[$i] = array_values($new_array[$i]);
  329. }
  330. $i++;
  331. }
  332. return $new_array;
  333. }
  334. else {
  335. return null;
  336. }
  337. }
  338. }
  339. /**********************************************************************
  340. * Function to get column meta data info pertaining to the last query
  341. * see docs for more info and usage
  342. */
  343. public function get_col_info($info_type="name",$col_offset=-1) {
  344. if ( $this->col_info ) {
  345. if ( $col_offset == -1 ) {
  346. $i=0;
  347. foreach($this->col_info as $col ) {
  348. $new_array[$i] = $col->{$info_type};
  349. $i++;
  350. }
  351. return $new_array;
  352. }
  353. else {
  354. return $this->col_info[$col_offset]->{$info_type};
  355. }
  356. }
  357. }
  358. /**********************************************************************
  359. * store_cache
  360. */
  361. public function store_cache($query,$is_insert) {
  362. // The would be cache file for this query
  363. $cache_file = $this->cache_dir.'/'.md5($query).'.sql.php';
  364. // disk caching of queries
  365. if ( $this->use_disk_cache && ( $this->cache_queries && ! $is_insert ) || ( $this->cache_inserts && $is_insert )) {
  366. if ( ! is_dir($this->cache_dir) ) {
  367. $this->register_error("Could not open cache dir: $this->cache_dir");
  368. $this->show_errors ? trigger_error("Could not open cache dir: $this->cache_dir",E_USER_WARNING) : null;
  369. }
  370. else {
  371. // Cache all result values
  372. $result_cache = array(
  373. 'col_info' => $this->col_info,
  374. 'last_result' => $this->last_result,
  375. 'num_rows' => $this->num_rows,
  376. 'return_value' => $this->num_rows);
  377. error_log ( serialize($result_cache), 3, $cache_file);
  378. }
  379. }
  380. }
  381. /**********************************************************************
  382. * get_cache
  383. */
  384. public function get_cache($query) {
  385. // The would be cache file for this query
  386. $cache_file = $this->cache_dir.'/'.md5($query).'.sql.php';
  387. // Try to get previously cached version
  388. if ( $this->use_disk_cache && file_exists($cache_file) ) {
  389. // Only use this cache file if less than 'cache_timeout' (hours)
  390. if ( (time() - filemtime($cache_file)) > ($this->cache_timeout*3600) ) {
  391. unlink($cache_file);
  392. }
  393. else {
  394. $result_cache = unserialize(file_get_contents($cache_file));
  395. $this->col_info = $result_cache['col_info'];
  396. $this->last_result = $result_cache['last_result'];
  397. $this->num_rows = $result_cache['num_rows'];
  398. $this->from_disk_cache = true;
  399. // If debug ALL queries
  400. $this->trace || $this->debug_all ? $this->debug() : null ;
  401. return $result_cache['return_value'];
  402. }
  403. }
  404. }
  405. /**********************************************************************
  406. * Dumps the contents of any input variable to screen in a nicely
  407. * formatted and easy to understand way - any type: Object, Var or Array
  408. */
  409. public function vardump($mixed='') {
  410. // Start outup buffering
  411. ob_start();
  412. echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";
  413. echo "<pre><font face=arial>";
  414. if ( ! $this->vardump_called ) {
  415. echo "<font color=800080><b>ezSQL</b> (v",EZSQL_VERSION,") <b>Variable Dump..</b></font>\n\n";
  416. }
  417. $var_type = gettype ($mixed);
  418. print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));
  419. echo "\n\n<b>Type:</b> ",ucfirst($var_type),"\n";
  420. echo "<b>Last Query</b> [",$this->num_queries,"]<b>:</b> ",($this->last_query?$this->last_query:"NULL"),"\n";
  421. echo "<b>Last Function Call:</b> ",($this->func_call?$this->func_call:"None"),"\n";
  422. echo "<b>Last Rows Returned:</b> ",count($this->last_result),"\n";
  423. echo "</font></pre></font></blockquote></td></tr></table>";
  424. echo "\n<hr size=1 noshade color=dddddd>";
  425. // Stop output buffering and capture debug HTML
  426. $html = ob_get_contents();
  427. ob_end_clean();
  428. // Only echo output if it is turned on
  429. if ( $this->debug_echo_is_on ) {
  430. echo $html;
  431. }
  432. $this->vardump_called = true;
  433. return $html;
  434. }
  435. /**********************************************************************
  436. * Displays the last query string that was sent to the database & a
  437. * table listing results (if there were any).
  438. * (abstracted into a seperate file to save server overhead).
  439. */
  440. public function debug() {
  441. // Start outup buffering
  442. ob_start();
  443. echo "<blockquote>";
  444. // Only show ezSQL credits once..
  445. if ( ! $this->debug_called ) {
  446. echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v",EZSQL_VERSION,") <b>Debug..</b></font><p>\n";
  447. }
  448. if ( $this->last_error ) {
  449. echo "<font face=arial size=2 color=000099><b>Last Error --</b> [<font color=000000><b>",$this->last_error,"</b></font>]<p>";
  450. }
  451. if ( $this->from_disk_cache ) {
  452. echo "<font face=arial size=2 color=000099><b>Results retrieved from disk cache</b></font><p>";
  453. }
  454. echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";
  455. echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
  456. echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
  457. echo "<blockquote>";
  458. if ( $this->col_info ) {
  459. // =====================================================
  460. // Results top rows
  461. echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
  462. echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
  463. for ( $i=0; $i < count($this->col_info); $i++ ) {
  464. 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>";
  465. }
  466. echo "</tr>";
  467. // ======================================================
  468. // print main results
  469. if ( $this->last_result ) {
  470. $i=0;
  471. foreach ( $this->get_results(null,ARRAY_N) as $one_row ) {
  472. $i++;
  473. echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
  474. foreach ( $one_row as $item ) {
  475. echo "<td nowrap><font face=arial size=2>$item</font></td>";
  476. }
  477. echo "</tr>";
  478. }
  479. } // if last result
  480. else {
  481. echo "<tr bgcolor=ffffff><td colspan=",(count($this->col_info)+1),"><font face=arial size=2>No Results</font></td></tr>";
  482. }
  483. echo "</table>";
  484. } // if col_info
  485. else {
  486. echo "<font face=arial size=2>No Results</font>";
  487. }
  488. echo "</blockquote></blockquote><hr noshade color=dddddd size=1>";
  489. // Stop output buffering and capture debug HTML
  490. $html = ob_get_contents();
  491. ob_end_clean();
  492. // Only echo output if it is turned on
  493. if ( $this->debug_echo_is_on ) {
  494. echo $html;
  495. }
  496. $this->debug_called = true;
  497. return $html;
  498. }
  499. }
  500. $scdb = new scdb(DB_USER, DB_PASS, DB_NAME, DB_HOST);
  501. ?>