PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/class-mysql.php

https://bitbucket.org/theskumar/go
PHP | 407 lines | 278 code | 37 blank | 92 comment | 64 complexity | cca3bf8326bf17542c93e07285eb48ae MD5 | raw file
  1. <?php
  2. /*
  3. +----------------------------------------------------------------+
  4. | |
  5. | ezSQL |
  6. | Copyright (c) 2006 Justin Vincent |
  7. | |
  8. | File Written By: |
  9. | - Justin Vincent (justin@visunet.ie) |
  10. | - http://php.justinvincent.com |
  11. | |
  12. | File Information: |
  13. | - MYSQL Database Class |
  14. | - class-mysql.php |
  15. | |
  16. +----------------------------------------------------------------+
  17. */
  18. ### ezSQL Constants. Might be defined in the WordPress environment if YOURLS plugin used.
  19. if( !defined('EZSQL_VERSION') )
  20. define('EZSQL_VERSION','2.0');
  21. if( !defined('OBJECT') )
  22. define('OBJECT','OBJECT',true);
  23. if( !defined('ARRAY_A') )
  24. define('ARRAY_A','ARRAY_A',true);
  25. if( !defined('ARRAY_N') )
  26. define('ARRAY_N','ARRAY_N',true);
  27. if( !defined('EZSQL_CORE_ERROR') )
  28. define('EZSQL_CORE_ERROR','ezSQLcore can not be used by itself (it is designed for use by database specific modules).');
  29. ### ezSQL Core Class
  30. // Core class containg common functions to manipulate query result sets once returned
  31. class ezSQLcore{
  32. var $trace = false; // same as $debug_all
  33. var $debug_all = false; // same as $trace
  34. var $debug_called = false;
  35. var $vardump_called = false;
  36. var $show_errors = false;
  37. var $num_queries = 0;
  38. var $last_query = null;
  39. var $last_error = null;
  40. var $col_info = null;
  41. var $captured_errors = array();
  42. var $all_queries = '';
  43. ## Constructor
  44. function ezSQLcore() { }
  45. ## Connect to DB - over-ridden by specific DB class
  46. function connect() { die(EZSQL_CORE_ERROR); }
  47. ## Select DB - over-ridden by specific DB class
  48. function select() { die(EZSQL_CORE_ERROR); }
  49. ## Basic Query - over-ridden by specific DB class
  50. function query() { die(EZSQL_CORE_ERROR); }
  51. ## Format a string correctly for safe insert - over-ridden by specific DB class
  52. function escape() { die(EZSQL_CORE_ERROR); }
  53. ## Return database specific system date syntax
  54. function sysdate() { die(EZSQL_CORE_ERROR); }
  55. ## Print SQL/DB error - over-ridden by specific DB class
  56. function register_error($err_str) {
  57. // Keep track of last error
  58. $this->last_error = $err_str;
  59. // Capture all errors to an error array no matter what happens
  60. $this->captured_errors[] = array ('error_str' => $err_str, 'query' => $this->last_query);
  61. }
  62. ## Show Errors
  63. function show_errors() { $this->show_errors = true; }
  64. ## Hide Errors
  65. function hide_errors() { $this->show_errors = false; }
  66. ## Kill cached query results
  67. function flush() {
  68. // Get rid of these
  69. $this->last_result = null;
  70. $this->col_info = null;
  71. $this->last_query = null;
  72. }
  73. ## Get one variable from the DB - see docs for more detail
  74. function get_var($query=null,$x=0,$y=0) {
  75. // Log how the function was called
  76. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  77. // If there is a query then perform it if not then use cached results..
  78. if ($query) {
  79. $this->query($query);
  80. }
  81. // Extract var out of cached results based x,y vals
  82. if ($this->last_result[$y]){
  83. $values = array_values(get_object_vars($this->last_result[$y]));
  84. }
  85. // If there is a value return it else return null
  86. return (isset($values[$x]) && $values[$x]!=='')?$values[$x]:null;
  87. }
  88. ## Get one row from the DB - see docs for more detail
  89. function get_row($query=null,$output=OBJECT,$y=0) {
  90. // Log how the function was called
  91. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  92. // If there is a query then perform it if not then use cached results..
  93. if ($query) {
  94. $this->query($query);
  95. }
  96. // If the output is an object then return object using the row offset..
  97. if ($output == OBJECT) {
  98. return $this->last_result[$y]?$this->last_result[$y]:null;
  99. // If the output is an associative array then return row as such..
  100. } elseif ($output == ARRAY_A) {
  101. return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null;
  102. // If the output is an numerical array then return row as such..
  103. } elseif ($output == ARRAY_N) {
  104. return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null;
  105. // If invalid output type was specified..
  106. } else {
  107. $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
  108. }
  109. }
  110. ## Function to get 1 column from the cached result set based in X index see docs for usage and info
  111. function get_col($query=null,$x=0) {
  112. // If there is a query then perform it if not then use cached results..
  113. if ($query) {
  114. $this->query($query);
  115. }
  116. // Extract the column values
  117. for ($i=0; $i < count($this->last_result); $i++) {
  118. $new_array[$i] = $this->get_var(null,$x,$i);
  119. }
  120. return $new_array;
  121. }
  122. ## Return the the query as a result set - see docs for more details
  123. function get_results($query=null, $output = OBJECT) {
  124. // Log how the function was called
  125. $this->func_call = "\$db->get_results(\"$query\", $output)";
  126. // If there is a query then perform it if not then use cached results..
  127. if ($query) {
  128. $this->query($query);
  129. }
  130. // Send back array of objects. Each row is an object
  131. if ($output == OBJECT) {
  132. return $this->last_result;
  133. } elseif ($output == ARRAY_A || $output == ARRAY_N) {
  134. if ($this->last_result) {
  135. $i=0;
  136. foreach($this->last_result as $row) {
  137. $new_array[$i] = get_object_vars($row);
  138. if ($output == ARRAY_N) {
  139. $new_array[$i] = array_values($new_array[$i]);
  140. }
  141. $i++;
  142. }
  143. return $new_array;
  144. } else {
  145. return null;
  146. }
  147. }
  148. }
  149. ## Function to get column meta data info pertaining to the last query see docs for more info and usage
  150. function get_col_info($info_type="name",$col_offset=-1) {
  151. if ($this->col_info) {
  152. if ($col_offset == -1) {
  153. $i=0;
  154. foreach($this->col_info as $col) {
  155. $new_array[$i] = $col->{$info_type};
  156. $i++;
  157. }
  158. return $new_array;
  159. } else {
  160. return $this->col_info[$col_offset]->{$info_type};
  161. }
  162. }
  163. }
  164. ## Dumps the contents of any input variable to screen in a nicely formatted and easy to understand way - any type: Object, Var or Array
  165. function vardump($mixed='') {
  166. echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";
  167. echo "<pre><font face=arial>";
  168. if (!$this->vardump_called) {
  169. echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";
  170. }
  171. $var_type = gettype ($mixed);
  172. print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));
  173. echo "\n\n<b>Type:</b> " . ucfirst($var_type) . "\n";
  174. echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query?$this->last_query:"NULL")."\n";
  175. echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";
  176. echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";
  177. echo "</font></pre></font></blockquote></td></tr></table>".$this->donation();
  178. echo "\n<hr size=1 noshade color=dddddd>";
  179. $this->vardump_called = true;
  180. }
  181. ## Alias for the above function
  182. function dumpvar($mixed) { $this->vardump($mixed); }
  183. ## Displays the last query string that was sent to the database & a table listing results (if there were any). (abstracted into a seperate file to save server overhead).
  184. function debug() {
  185. echo "<blockquote>";
  186. // Only show ezSQL credits once..
  187. if (!$this->debug_called) {
  188. echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";
  189. }
  190. if ($this->last_error) {
  191. echo "<font face=arial size=2 color=000099><b>Last Error --</b> [<font color=000000><b>$this->last_error</b></font>]<p>";
  192. }
  193. echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";
  194. echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
  195. echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
  196. echo "<blockquote>";
  197. if ($this->col_info) {
  198. // Results top rows
  199. echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
  200. echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
  201. for ($i=0; $i < count($this->col_info); $i++) {
  202. 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>";
  203. }
  204. echo "</tr>";
  205. // print main results
  206. if ($this->last_result) {
  207. $i=0;
  208. foreach ($this->get_results(null,ARRAY_N) as $one_row) {
  209. $i++;
  210. echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
  211. foreach ($one_row as $item) {
  212. echo "<td nowrap><font face=arial size=2>$item</font></td>";
  213. }
  214. echo "</tr>";
  215. }
  216. } else {
  217. echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";
  218. }
  219. echo "</table>";
  220. } else {
  221. echo "<font face=arial size=2>No Results</font>";
  222. }
  223. echo "</blockquote></blockquote>".$this->donation()."<hr noshade color=dddddd size=1>";
  224. $this->debug_called = true;
  225. }
  226. ## Naughty little function to ask for some remuniration!
  227. function donation() {
  228. 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>";
  229. }
  230. }
  231. ### ezSQL MYSQL Class Variables
  232. $ezsql_mysql_str = array
  233. (
  234. 1 => 'Require $dbuser and $dbpassword to connect to a database server',
  235. 2 => 'Error establishing mySQL database connection. Correct user/password? Correct hostname? Database server running?',
  236. 3 => 'Require $dbname to select a database',
  237. 4 => 'mySQL database connection is not active',
  238. 5 => 'Unexpected error while trying to select database'
  239. );
  240. 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');
  241. 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');
  242. ### ezSQL MYSQL Class
  243. class ezSQL_mysql extends ezSQLcore {
  244. ## Constructor - allow the user to perform a qucik connect at the same time as initialising the ezSQL_mysql class
  245. function ezSQL_mysql($dbuser='', $dbpassword='', $dbname='', $dbhost='localhost') {
  246. if ($dbuser && $dbname) {
  247. $this->quick_connect($dbuser, $dbpassword, $dbname, $dbhost);
  248. }
  249. }
  250. ## Short hand way to connect to mySQL database server and select a mySQL database at the same time
  251. function quick_connect($dbuser='', $dbpassword='', $dbname='', $dbhost='localhost') {
  252. $return_val = false;
  253. if ( ! $this->connect($dbuser, $dbpassword, $dbhost,true) ) ;
  254. else if ( ! $this->select($dbname) ) ;
  255. else $return_val = true;
  256. return $return_val;
  257. }
  258. ## Try to connect to mySQL database server
  259. function connect($dbuser='', $dbpassword='', $dbhost='localhost'){
  260. global $ezsql_mysql_str; $return_val = false;
  261. // Must have a user and a password
  262. if (!$dbuser){
  263. $this->register_error($ezsql_mysql_str[1].' in '.__FILE__.' on line '.__LINE__);
  264. $this->show_errors ? trigger_error($ezsql_mysql_str[1],E_USER_WARNING) : null;
  265. // Try to establish the server database handle
  266. } else if (!$this->dbh = @mysql_connect($dbhost,$dbuser,$dbpassword)) {
  267. $this->register_error($ezsql_mysql_str[2].' in '.__FILE__.' on line '.__LINE__);
  268. $this->show_errors ? trigger_error($ezsql_mysql_str[2],E_USER_WARNING) : null;
  269. } else {
  270. $return_val = true;
  271. }
  272. return $return_val;
  273. }
  274. ## Close
  275. function close() {
  276. return mysql_close($this->dbh);
  277. }
  278. ## Try to select a mySQL database
  279. function select($dbname='') {
  280. global $ezsql_mysql_str; $return_val = false;
  281. // Must have a database name
  282. if (!$dbname) {
  283. $this->register_error($ezsql_mysql_str[3].' in '.__FILE__.' on line '.__LINE__);
  284. $this->show_errors ? trigger_error($ezsql_mysql_str[3],E_USER_WARNING) : null;
  285. // Must have an active database connection
  286. } else if (!$this->dbh) {
  287. $this->register_error($ezsql_mysql_str[4].' in '.__FILE__.' on line '.__LINE__);
  288. $this->show_errors ? trigger_error($ezsql_mysql_str[4],E_USER_WARNING) : null;
  289. // Try to connect to the database
  290. } else if (!@mysql_select_db($dbname,$this->dbh)) {
  291. // Try to get error supplied by mysql if not use our own
  292. if ( !$str = @mysql_error($this->dbh)) {
  293. $str = $ezsql_mysql_str[5];
  294. }
  295. $this->register_error($str.' in '.__FILE__.' on line '.__LINE__);
  296. $this->show_errors ? trigger_error($str,E_USER_WARNING) : null;
  297. } else {
  298. $return_val = true;
  299. }
  300. return $return_val;
  301. }
  302. ## Format a mySQL string correctly for safe mySQL insert (no mater if magic quotes are on or not)
  303. function escape($str) {
  304. return mysql_escape_string(stripslashes($str));
  305. }
  306. ## Return mySQL specific system date syntax
  307. function sysdate() {
  308. return 'NOW()';
  309. }
  310. ## Perform mySQL query and try to detirmin result value
  311. function query($query) {
  312. // For reg expressions
  313. $query = trim($query);
  314. // Initialise return
  315. $return_val = 0;
  316. // Flush cached values..
  317. $this->flush();
  318. // Log how the function was called
  319. $this->func_call = "\$db->query(\"$query\")";
  320. // Keep track of the last query for debug..
  321. $this->last_query = $query;
  322. // Perform the query via std mysql_query function..
  323. $this->result = @mysql_query($query,$this->dbh);
  324. $this->num_queries++;
  325. $this->all_queries .= $query.'<br />';
  326. // If there is an error then take note of it..
  327. if ($str = @mysql_error($this->dbh)) {
  328. $this->register_error($str);
  329. $this->show_errors ? trigger_error($str,E_USER_WARNING) : null;
  330. return false;
  331. }
  332. // Query was an insert, delete, update, replace
  333. if (preg_match("/^(insert|delete|update|replace)\s+/i",$query)) {
  334. $this->rows_affected = @mysql_affected_rows();
  335. // Take note of the insert_id
  336. if (preg_match("/^(insert|replace)\s+/i",$query)) {
  337. $this->insert_id = @mysql_insert_id($this->dbh);
  338. }
  339. // Return number fo rows affected
  340. $return_val = $this->rows_affected;
  341. // Query was a select
  342. } else {
  343. // Take note of column info
  344. $i=0;
  345. while ($i < @mysql_num_fields($this->result)) {
  346. $this->col_info[$i] = @mysql_fetch_field($this->result);
  347. $i++;
  348. }
  349. // Store Query Results
  350. $num_rows=0;
  351. while ($row = @mysql_fetch_object($this->result)) {
  352. // Store relults as an objects within main array
  353. $this->last_result[$num_rows] = $row;
  354. $num_rows++;
  355. }
  356. @mysql_free_result($this->result);
  357. // Log number of rows the query returned
  358. $this->num_rows = $num_rows;
  359. // Return number of rows selected
  360. $return_val = $this->num_rows;
  361. }
  362. // If debug ALL queries
  363. $this->trace || $this->debug_all ? $this->debug() : null ;
  364. return $return_val;
  365. }
  366. function mysql_version() {
  367. return mysql_get_server_info( $this->dbh ) ;
  368. }
  369. }
  370. ?>