PageRenderTime 44ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/php/extlib/ezsql/ezsql_mysql.php

http://github.com/openmelody/melody
PHP | 518 lines | 304 code | 116 blank | 98 comment | 40 complexity | f25c61a94d1c0ec50abb457b89fc1a90 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.0, LGPL-2.1
  1. <?php
  2. // ==================================================================
  3. // Author: Justin Vincent (justin@visunet.ie)
  4. // Web: http://php.justinvincent.com
  5. // Name: ezSQL
  6. // Desc: Class to make it very easy to deal with mySQL database connections.
  7. //
  8. // !! IMPORTANT !!
  9. //
  10. // Please send me a mail telling me what you think of ezSQL
  11. // and what your using it for!! Cheers. [ justin@visunet.ie ]
  12. //
  13. // ==================================================================
  14. // User Settings -- CHANGE HERE
  15. define("EZSQL_DB_USER", ""); // <-- mysql db user
  16. define("EZSQL_DB_PASSWORD", ""); // <-- mysql db password
  17. define("EZSQL_DB_NAME", "mysql"); // <-- mysql db pname
  18. define("EZSQL_DB_HOST", "localhost"); // <-- mysql server host
  19. // ==================================================================
  20. // ezSQL Constants
  21. define("EZSQL_VERSION","1.26");
  22. define("OBJECT","OBJECT",true);
  23. define("ARRAY_A","ARRAY_A",true);
  24. define("ARRAY_N","ARRAY_N",true);
  25. // ==================================================================
  26. // The Main Class
  27. class ezsql {
  28. var $trace = false; // same as $debug_all
  29. var $debug_all = false; // same as $trace
  30. var $show_errors = true;
  31. var $num_queries = 0;
  32. var $last_query;
  33. var $col_info;
  34. var $debug_called;
  35. var $vardump_called;
  36. // ==================================================================
  37. // DB Constructor - connects to the server and selects a database
  38. function db($dbuser, $dbpassword, $dbname, $dbhost, $dbport = '', $dbsocket = '')
  39. {
  40. // dbsocket is prior than dbport
  41. if (! empty($dbport) ) {
  42. $dbhost .= ":$dbport";
  43. } else {
  44. if (! empty($dbsocket) ) $dbhost .= ":$dbsocket";
  45. }
  46. $this->dbh = @mysql_connect($dbhost,$dbuser,$dbpassword);
  47. if ( ! $this->dbh )
  48. {
  49. $this->print_error("<ol><b>Error establishing a database connection!</b><li>Are you sure you have the correct user/password?<li>Are you sure that you have typed the correct hostname?<li>Are you sure that the database server is running?</ol>");
  50. }
  51. $this->select($dbname);
  52. }
  53. // ==================================================================
  54. // Select a DB (if another one needs to be selected)
  55. function select($db)
  56. {
  57. if ( !@mysql_select_db($db,$this->dbh))
  58. {
  59. $this->print_error("<ol><b>Error selecting database <u>$db</u>!</b><li>Are you sure it exists?<li>Are you sure there is a valid database connection?</ol>");
  60. }
  61. }
  62. // ====================================================================
  63. // Format a string correctly for safe insert under all PHP conditions
  64. function escape($str)
  65. {
  66. return mysql_escape_string(stripslashes($str));
  67. }
  68. // ==================================================================
  69. // Print SQL/DB error.
  70. function print_error($str = "")
  71. {
  72. // All erros go to the global error array $EZSQL_ERROR..
  73. global $EZSQL_ERROR;
  74. // If no special error string then use mysql default..
  75. if ( !$str )
  76. {
  77. $str = mysql_error($this->dbh);
  78. $error_no = mysql_errno($this->dbh);
  79. }
  80. // Log this error to the global array..
  81. $EZSQL_ERROR[] = array
  82. (
  83. "query" => $this->last_query,
  84. "error_str" => $str,
  85. "error_no" => $error_no
  86. );
  87. // Is error output turned on or not..
  88. if ( $this->show_errors )
  89. {
  90. // If there is an error then take note of it
  91. print "<blockquote><font face=arial size=2 color=ff0000>";
  92. print "<b>SQL/DB Error --</b> ";
  93. print "[<font color=000077>$str</font>]";
  94. print "</font></blockquote>";
  95. }
  96. else
  97. {
  98. return false;
  99. }
  100. }
  101. // ==================================================================
  102. // Turn error handling on or off..
  103. function show_errors()
  104. {
  105. $this->show_errors = true;
  106. }
  107. function hide_errors()
  108. {
  109. $this->show_errors = false;
  110. }
  111. // ==================================================================
  112. // Kill cached query results
  113. function flush()
  114. {
  115. // Get rid of these
  116. $this->last_result = null;
  117. $this->col_info = null;
  118. $this->last_query = null;
  119. }
  120. // ==================================================================
  121. // Basic Query - see docs for more detail
  122. function query($query)
  123. {
  124. // For reg expressions
  125. $query = trim($query);
  126. // initialise return
  127. $return_val = 0;
  128. // Flush cached values..
  129. $this->flush();
  130. // Log how the function was called
  131. $this->func_call = "\$db->query(\"$query\")";
  132. // Keep track of the last query for debug..
  133. $this->last_query = $query;
  134. // Perform the query via std mysql_query function..
  135. $this->result = @mysql_query($query,$this->dbh);
  136. $this->num_queries++;
  137. // If there is an error then take note of it..
  138. if ( mysql_error() )
  139. {
  140. $this->print_error();
  141. return false;
  142. }
  143. // Query was an insert, delete, update, replace
  144. if ( preg_match("/^(insert|delete|update|replace)\s+/i",$query) )
  145. {
  146. $this->rows_affected = mysql_affected_rows();
  147. // Take note of the insert_id
  148. if ( preg_match("/^(insert|replace)\s+/i",$query) )
  149. {
  150. $this->insert_id = mysql_insert_id($this->dbh);
  151. }
  152. // Return number fo rows affected
  153. $return_val = $this->rows_affected;
  154. }
  155. // Query was an select
  156. else
  157. {
  158. // Take note of column info
  159. $i=0;
  160. while ($i < @mysql_num_fields($this->result))
  161. {
  162. $this->col_info[$i] = @mysql_fetch_field($this->result);
  163. $i++;
  164. }
  165. // Store Query Results
  166. $num_rows=0;
  167. while ( $row = @mysql_fetch_object($this->result) )
  168. {
  169. // Store relults as an objects within main array
  170. $this->last_result[$num_rows] = $row;
  171. $num_rows++;
  172. }
  173. @mysql_free_result($this->result);
  174. // Log number of rows the query returned
  175. $this->num_rows = $num_rows;
  176. // Return number of rows selected
  177. $return_val = $this->num_rows;
  178. }
  179. // If debug ALL queries
  180. $this->trace || $this->debug_all ? $this->debug() : null ;
  181. return $return_val;
  182. }
  183. // ==================================================================
  184. // Get one variable from the DB - see docs for more detail
  185. function get_var($query=null,$x=0,$y=0)
  186. {
  187. // Log how the function was called
  188. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  189. // If there is a query then perform it if not then use cached results..
  190. if ( $query )
  191. {
  192. $this->query($query);
  193. }
  194. // Extract var out of cached results based x,y vals
  195. if ( $this->last_result[$y] )
  196. {
  197. $values = array_values(get_object_vars($this->last_result[$y]));
  198. }
  199. // If there is a value return it else return null
  200. return (isset($values[$x]) && $values[$x]!=='')?$values[$x]:null;
  201. }
  202. // ==================================================================
  203. // Get one row from the DB - see docs for more detail
  204. function get_row($query=null,$output=OBJECT,$y=0)
  205. {
  206. // Log how the function was called
  207. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  208. // If there is a query then perform it if not then use cached results..
  209. if ( $query )
  210. {
  211. $this->query($query);
  212. }
  213. // If the output is an object then return object using the row offset..
  214. if ( $output == OBJECT )
  215. {
  216. return $this->last_result[$y]?$this->last_result[$y]:null;
  217. }
  218. // If the output is an associative array then return row as such..
  219. elseif ( $output == ARRAY_A )
  220. {
  221. return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null;
  222. }
  223. // If the output is an numerical array then return row as such..
  224. elseif ( $output == ARRAY_N )
  225. {
  226. return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null;
  227. }
  228. // If invalid output type was specified..
  229. else
  230. {
  231. $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
  232. }
  233. }
  234. // ==================================================================
  235. // Function to get 1 column from the cached result set based in X index
  236. // se docs for usage and info
  237. function get_col($query=null,$x=0)
  238. {
  239. // If there is a query then perform it if not then use cached results..
  240. if ( $query )
  241. {
  242. $this->query($query);
  243. }
  244. // Extract the column values
  245. for ( $i=0; $i < count($this->last_result); $i++ )
  246. {
  247. $new_array[$i] = $this->get_var(null,$x,$i);
  248. }
  249. return $new_array;
  250. }
  251. // ==================================================================
  252. // Return the the query as a result set - see docs for more details
  253. function get_results($query=null, $output = OBJECT)
  254. {
  255. // Log how the function was called
  256. $this->func_call = "\$db->get_results(\"$query\", $output)";
  257. // If there is a query then perform it if not then use cached results..
  258. if ( $query )
  259. {
  260. $this->query($query);
  261. }
  262. // Send back array of objects. Each row is an object
  263. if ( $output == OBJECT )
  264. {
  265. return $this->last_result;
  266. }
  267. elseif ( $output == ARRAY_A || $output == ARRAY_N )
  268. {
  269. if ( $this->last_result )
  270. {
  271. $i=0;
  272. foreach( $this->last_result as $row )
  273. {
  274. $new_array[$i] = get_object_vars($row);
  275. if ( $output == ARRAY_N )
  276. {
  277. $new_array[$i] = array_values($new_array[$i]);
  278. }
  279. $i++;
  280. }
  281. return $new_array;
  282. }
  283. else
  284. {
  285. return null;
  286. }
  287. }
  288. }
  289. // ==================================================================
  290. // Function to get column meta data info pertaining to the last query
  291. // see docs for more info and usage
  292. function get_col_info($info_type="name",$col_offset=-1)
  293. {
  294. if ( $this->col_info )
  295. {
  296. if ( $col_offset == -1 )
  297. {
  298. $i=0;
  299. foreach($this->col_info as $col )
  300. {
  301. $new_array[$i] = $col->{$info_type};
  302. $i++;
  303. }
  304. return $new_array;
  305. }
  306. else
  307. {
  308. return $this->col_info[$col_offset]->{$info_type};
  309. }
  310. }
  311. }
  312. // ==================================================================
  313. // Dumps the contents of any input variable to screen in a nicely
  314. // formatted and easy to understand way - any type: Object, Var or Array
  315. function vardump($mixed='')
  316. {
  317. echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";
  318. echo "<pre><font face=arial>";
  319. if ( ! $this->vardump_called )
  320. {
  321. echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";
  322. }
  323. $var_type = gettype ($mixed);
  324. print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));
  325. echo "\n\n<b>Type:</b> " . ucfirst($var_type) . "\n";
  326. echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query?$this->last_query:"NULL")."\n";
  327. echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";
  328. echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";
  329. echo "</font></pre></font></blockquote></td></tr></table>".$this->donation();
  330. echo "\n<hr size=1 noshade color=dddddd>";
  331. $this->vardump_called = true;
  332. }
  333. // Alias for the above function
  334. function dumpvar($mixed)
  335. {
  336. $this->vardump($mixed);
  337. }
  338. // ==================================================================
  339. // Displays the last query string that was sent to the database & a
  340. // table listing results (if there were any).
  341. // (abstracted into a seperate file to save server overhead).
  342. function debug()
  343. {
  344. echo "<blockquote>";
  345. // Only show ezSQL credits once..
  346. if ( ! $this->debug_called )
  347. {
  348. echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";
  349. }
  350. echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";
  351. echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
  352. echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
  353. echo "<blockquote>";
  354. if ( $this->col_info )
  355. {
  356. // =====================================================
  357. // Results top rows
  358. echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
  359. echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
  360. for ( $i=0; $i < count($this->col_info); $i++ )
  361. {
  362. 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>";
  363. }
  364. echo "</tr>";
  365. // ======================================================
  366. // print main results
  367. if ( $this->last_result )
  368. {
  369. $i=0;
  370. foreach ( $this->get_results(null,ARRAY_N) as $one_row )
  371. {
  372. $i++;
  373. echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
  374. foreach ( $one_row as $item )
  375. {
  376. echo "<td nowrap><font face=arial size=2>$item</font></td>";
  377. }
  378. echo "</tr>";
  379. }
  380. } // if last result
  381. else
  382. {
  383. echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";
  384. }
  385. echo "</table>";
  386. } // if col_info
  387. else
  388. {
  389. echo "<font face=arial size=2>No Results</font>";
  390. }
  391. echo "</blockquote></blockquote>".$this->donation()."<hr noshade color=dddddd size=1>";
  392. $this->debug_called = true;
  393. }
  394. // =======================================================
  395. // Naughty little function to ask for some remuniration!
  396. function donation()
  397. {
  398. 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>";
  399. }
  400. }
  401. #$db = new db(EZSQL_DB_USER, EZSQL_DB_PASSWORD, EZSQL_DB_NAME, EZSQL_DB_HOST);
  402. ?>