PageRenderTime 26ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/vendor/dbobject/class.database.php

https://github.com/yeargin/photo-vote-php
PHP | 309 lines | 222 code | 50 blank | 37 comment | 33 complexity | 05b68a94302b6649b90fcfb72660c9d7 MD5 | raw file
  1. <?PHP
  2. class Database
  3. {
  4. // Singleton object. Leave $me alone.
  5. private static $me;
  6. public $readDB;
  7. public $writeDB;
  8. public $readHost;
  9. public $writeHost;
  10. public $name;
  11. public $readUsername;
  12. public $writeUsername;
  13. public $readPassword;
  14. public $writePassword;
  15. public $onError; // Can be '', 'die', or 'redirect'
  16. public $emailOnError;
  17. public $queries;
  18. public $result;
  19. public $emailTo; // Where to send an error report
  20. public $emailSubject;
  21. public $errorUrl; // Where to redirect the user on error
  22. // Singleton constructor
  23. private function __construct()
  24. {
  25. /* If loading througha config.php file */
  26. $this->readHost = DB_READ_HOST;
  27. $this->writeHost = DB_WRITE_HOST;
  28. $this->name = DB_NAME;
  29. $this->readUsername = DB_READ_USERNAME;
  30. $this->writeUsername = DB_WRITE_USERNAME;
  31. $this->readPassword = DB_READ_PASSWORD;
  32. $this->writePassword = DB_WRITE_PASSWORD;
  33. $this->onError = DB_ON_ERROR;
  34. $this->emailOnError = DB_EMAIL_ON_ERROR;
  35. /* If using Simple-PHP-Framework's config class ... */
  36. // $this->readHost = Config::get('dbReadHost');
  37. // $this->writeHost = Config::get('dbWriteHost');
  38. // $this->name = Config::get('dbName');
  39. // $this->readUsername = Config::get('dbReadUsername');
  40. // $this->writeUsername = Config::get('dbWriteUsername');
  41. // $this->readPassword = Config::get('dbReadPassword');
  42. // $this->writePassword = Config::get('dbWritePassword');
  43. // $this->onError = Config::get('dbOnError');
  44. // $this->emailOnError = Config::get('dbEmailOnError');
  45. $this->readDB = false;
  46. $this->writeDB = false;
  47. $this->queries = array();
  48. }
  49. // Get Singleton object
  50. public static function getDatabase()
  51. {
  52. if(is_null(self::$me))
  53. self::$me = new Database();
  54. return self::$me;
  55. }
  56. // Do we have a valid read-only database connection?
  57. public function isReadConnected()
  58. {
  59. return is_resource($this->readDB) && get_resource_type($this->readDB) == 'mysql link';
  60. }
  61. // Do we have a valid read/write database connection?
  62. public function isWriteConnected()
  63. {
  64. return is_resource($this->writeDB) && get_resource_type($this->writeDB) == 'mysql link';
  65. }
  66. // Do we have a valid database connection and have we selected a database?
  67. public function databaseSelected()
  68. {
  69. if(!$this->isReadConnected()) return false;
  70. $result = mysql_list_tables($this->name, $this->readDB);
  71. return is_resource($result);
  72. }
  73. public function readConnect()
  74. {
  75. $this->readDB = mysql_connect($this->readHost, $this->readUsername, $this->readPassword) or $this->notify();
  76. if($this->readDB === false) return false;
  77. if(!empty($this->name))
  78. mysql_select_db($this->name, $this->readDB) or $this->notify();
  79. return $this->isReadConnected();
  80. }
  81. public function writeConnect()
  82. {
  83. $this->writeDB = mysql_connect($this->writeHost, $this->writeUsername, $this->writePassword) or $this->notify();
  84. if($this->writeDB === false) return false;
  85. if(!empty($this->name))
  86. mysql_select_db($this->name, $this->writeDB) or $this->notify();
  87. return $this->isWriteConnected();
  88. }
  89. public function query($sql, $args_to_prepare = null, $exception_on_missing_args = true)
  90. {
  91. // Read or Write connection?
  92. $sql = trim($sql);
  93. if(preg_match('/^(INSERT|UPDATE|REPLACE|DELETE)/i', $sql) == 0)
  94. {
  95. if(!$this->isReadConnected())
  96. $this->readConnect();
  97. $the_db = $this->readDB;
  98. }
  99. else
  100. {
  101. if(!$this->isWriteConnected())
  102. $this->writeConnect();
  103. $the_db = $this->writeDB;
  104. }
  105. // Allow for prepared arguments. Example:
  106. // query("SELECT * FROM table WHERE id = :id:", array('id' => $some_val));
  107. if(is_array($args_to_prepare))
  108. {
  109. foreach($args_to_prepare as $name => $val)
  110. {
  111. $val = $this->quote($val);
  112. $sql = str_replace(":$name:", $val, $sql, $count);
  113. if($exception_on_missing_args && (0 == $count))
  114. throw new Exception(":$name: was not found in prepared SQL query.");
  115. }
  116. }
  117. $this->queries[] = $sql;
  118. $this->result = mysql_query($sql, $the_db) or $this->notify();
  119. return $this->result;
  120. }
  121. // Returns the number of rows.
  122. // You can pass in nothing, a string, or a db result
  123. public function numRows($arg = null)
  124. {
  125. $result = $this->resulter($arg);
  126. return ($result !== false) ? mysql_num_rows($result) : false;
  127. }
  128. // Returns true / false if the result has one or more rows
  129. public function hasRows($arg = null)
  130. {
  131. $result = $this->resulter($arg);
  132. return is_resource($result) && (mysql_num_rows($result) > 0);
  133. }
  134. // Returns the number of rows affected by the previous WRITE operation
  135. public function affectedRows()
  136. {
  137. if(!$this->isWriteConnected()) return false;
  138. return mysql_affected_rows($this->writeDB);
  139. }
  140. // Returns the auto increment ID generated by the previous insert statement
  141. public function insertId()
  142. {
  143. if(!$this->isWriteConnected()) return false;
  144. return mysql_insert_id($this->writeDB);
  145. }
  146. // Returns a single value.
  147. // You can pass in nothing, a string, or a db result
  148. public function getValue($arg = null)
  149. {
  150. $result = $this->resulter($arg);
  151. return $this->hasRows($result) ? mysql_result($result, 0, 0) : false;
  152. }
  153. // Returns an array of the first value in each row.
  154. // You can pass in nothing, a string, or a db result
  155. public function getValues($arg = null)
  156. {
  157. $result = $this->resulter($arg);
  158. if(!$this->hasRows($result)) return array();
  159. $values = array();
  160. mysql_data_seek($result, 0);
  161. while($row = mysql_fetch_array($result, MYSQL_ASSOC))
  162. $values[] = array_pop($row);
  163. return $values;
  164. }
  165. // Returns the first row.
  166. // You can pass in nothing, a string, or a db result
  167. public function getRow($arg = null)
  168. {
  169. $result = $this->resulter($arg);
  170. return $this->hasRows($result) ? mysql_fetch_array($result, MYSQL_ASSOC) : false;
  171. }
  172. // Returns an array of all the rows.
  173. // You can pass in nothing, a string, or a db result
  174. public function getRows($arg = null)
  175. {
  176. $result = $this->resulter($arg);
  177. if(!$this->hasRows($result)) return array();
  178. $rows = array();
  179. mysql_data_seek($result, 0);
  180. while($row = mysql_fetch_array($result, MYSQL_ASSOC))
  181. $rows[] = $row;
  182. return $rows;
  183. }
  184. // Escapes a value and wraps it in single quotes.
  185. public function quote($var)
  186. {
  187. return "'" . $this->escape($var) . "'";
  188. }
  189. // Escapes a value.
  190. public function escape($var)
  191. {
  192. if(!$this->isReadConnected()) $this->readConnect();
  193. return mysql_real_escape_string($var, $this->readDB);
  194. }
  195. public function numQueries()
  196. {
  197. return count($this->queries);
  198. }
  199. public function lastQuery()
  200. {
  201. if($this->numQueries() > 0)
  202. return $this->queries[$this->numQueries() - 1];
  203. else
  204. return false;
  205. }
  206. private function notify()
  207. {
  208. if($this->emailOnError === true)
  209. {
  210. $globals = print_r($GLOBALS, true);
  211. $msg = '';
  212. $msg .= "Url: " . full_url() . "\n";
  213. $msg .= "Date: " . dater() . "\n";
  214. $msg .= "Server: " . $_SERVER['SERVER_NAME'] . "\n";
  215. $msg .= "ReadDB Error:\n" . mysql_error($this->readDB) . "\n\n";
  216. $msg .= "WriteDB Error:\n" . mysql_error($this->writeDB) . "\n\n";
  217. ob_start();
  218. debug_print_backtrace();
  219. $trace = ob_get_contents();
  220. ob_end_clean();
  221. $msg .= $trace . "\n\n";
  222. $msg .= $globals;
  223. mail($this->emailTo, $this->emailSubject, $msg);
  224. }
  225. if($this->onError == 'die')
  226. {
  227. echo "<p style='border:5px solid red;background-color:#fff;padding:5px;'><strong>Read Database Error:</strong><br/>" . mysql_error($this->readDB) . "</p>";
  228. echo "<p style='border:5px solid red;background-color:#fff;padding:5px;'><strong>Write Database Error:</strong><br/>" . mysql_error($this->writeDB) . "</p>";
  229. echo "<p style='border:5px solid red;background-color:#fff;padding:5px;'><strong>Last Query:</strong><br/>" . $this->lastQuery() . "</p>";
  230. echo "<pre>";
  231. debug_print_backtrace();
  232. echo "</pre>";
  233. exit;
  234. }
  235. if($this->onError == 'redirect')
  236. {
  237. redirect($this->errorUrl);
  238. }
  239. }
  240. // Takes nothing, a MySQL result, or a query string and returns
  241. // the correspsonding MySQL result resource or false if none available.
  242. private function resulter($arg = null)
  243. {
  244. if(is_null($arg) && is_resource($this->result))
  245. return $this->result;
  246. elseif(is_resource($arg))
  247. return $arg;
  248. elseif(is_string($arg))
  249. {
  250. $this->query($arg);
  251. if(is_resource($this->result))
  252. return $this->result;
  253. else
  254. return false;
  255. }
  256. else
  257. return false;
  258. }
  259. }