PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/php/extlib/ezsql/ezsql_mssqlserver.php

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