PageRenderTime 34ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/_bin/@dbs.php

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