PageRenderTime 44ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/bblog/libs/ez_sql.php

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