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

/htdocs/classes/Database.singleton.php

https://github.com/Senkstyla/fb-imprint
PHP | 358 lines | 200 code | 74 blank | 84 comment | 43 complexity | 1dd30f17f24c6aeb081f2f566d4b3b6f MD5 | raw file
  1. <?php
  2. /**
  3. *
  4. */
  5. class Database
  6. {
  7. // debug flag for showing error messages
  8. public $debug = true;
  9. public $errno = 0;
  10. // Store the single instance of Database
  11. private static $instance;
  12. private $server = ""; //database server
  13. private $user = ""; //database login name
  14. private $pass = ""; //database login password
  15. private $database = ""; //database name
  16. private $error = "";
  17. #######################
  18. //number of rows affected by SQL query
  19. public $affected_rows = 0;
  20. private $link_id = 0;
  21. private $query_id = 0;
  22. /**
  23. * @param null $server
  24. * @param null $user
  25. * @param null $pass
  26. * @param null $database
  27. */
  28. private function __construct($server = null, $user = null, $pass = null, $database = null)
  29. {
  30. // error catching if not passed in
  31. if ($server == null || $user == null || $database == null) {
  32. $this->oops("Database information must be passed in when the object is first created.");
  33. }
  34. $this->server = $server;
  35. $this->user = $user;
  36. $this->pass = $pass;
  37. $this->database = $database;
  38. }
  39. #-#constructor()
  40. /**
  41. * @static
  42. * @param null $server
  43. * @param null $user
  44. * @param null $pass
  45. * @param null $database
  46. * @return Database
  47. */
  48. public static function obtain($server = null, $user = null, $pass = null, $database = null)
  49. {
  50. if (!self::$instance) {
  51. self::$instance = new Database($server, $user, $pass, $database);
  52. }
  53. return self::$instance;
  54. }
  55. #-#obtain()
  56. #-#############################################
  57. # desc: connect and select database using vars above
  58. # Param: $new_link can force connect() to open a new link, even if mysql_connect() was called before with the same parameters
  59. public function connect($new_link = false)
  60. {
  61. $this->link_id = @mysql_connect($this->server, $this->user, $this->pass, $new_link);
  62. if (!$this->link_id) { //open failed
  63. $this->oops("Could not connect to server: <b>$this->server</b>.");
  64. }
  65. if (!@mysql_select_db($this->database, $this->link_id)) { //no database
  66. $this->oops("Could not open database: <b>$this->database</b>.");
  67. }
  68. mysql_query("SET NAMES 'utf8'", $this->link_id);
  69. // unset the data so it can't be dumped
  70. $this->server = '';
  71. $this->user = '';
  72. $this->pass = '';
  73. $this->database = '';
  74. }
  75. #-#connect()
  76. #-#############################################
  77. # desc: close the connection
  78. public function close()
  79. {
  80. if (!@mysql_close($this->link_id)) {
  81. $this->oops("Connection close failed.");
  82. }
  83. }
  84. #-#close()
  85. #-#############################################
  86. # Desc: escapes characters to be mysql ready
  87. # Param: string
  88. # returns: string
  89. public function escape($string)
  90. {
  91. if (get_magic_quotes_runtime()) $string = stripslashes($string);
  92. return @mysql_real_escape_string($string, $this->link_id);
  93. }
  94. #-#escape()
  95. #-#############################################
  96. # Desc: executes SQL query to an open connection
  97. # Param: (MySQL query) to execute
  98. # returns: (query_id) for fetching results etc
  99. public function query($sql)
  100. {
  101. // do query
  102. $this->query_id = @mysql_query($sql, $this->link_id);
  103. if (!$this->query_id) {
  104. $this->oops("<b>MySQL Query fail:</b> $sql");
  105. return 0;
  106. }
  107. $this->affected_rows = @mysql_affected_rows($this->link_id);
  108. return $this->query_id;
  109. }
  110. #-#query()
  111. #-#############################################
  112. # desc: does a query, fetches the first row only, frees resultset
  113. # param: (MySQL query) the query to run on server
  114. # returns: array of fetched results
  115. public function query_first($query_string)
  116. {
  117. $query_id = $this->query($query_string);
  118. $out = $this->fetch($query_id);
  119. $this->free_result($query_id);
  120. return $out;
  121. }
  122. #-#query_first()
  123. #-#############################################
  124. # desc: fetches and returns results one line at a time
  125. # param: query_id for mysql run. if none specified, last used
  126. # return: (array) fetched record(s)
  127. public function fetch($query_id = -1)
  128. {
  129. // retrieve row
  130. if ($query_id != -1) {
  131. $this->query_id = $query_id;
  132. }
  133. if (isset($this->query_id)) {
  134. $record = @mysql_fetch_assoc($this->query_id);
  135. } else {
  136. $this->oops("Invalid query_id: <b>$this->query_id</b>. Records could not be fetched.");
  137. }
  138. return $record;
  139. }
  140. #-#fetch()
  141. #-#############################################
  142. # desc: returns all the results (not one row)
  143. # param: (MySQL query) the query to run on server
  144. # returns: assoc array of ALL fetched results
  145. public function fetch_array($sql)
  146. {
  147. $query_id = $this->query($sql);
  148. $out = array();
  149. while ($row = $this->fetch($query_id)) {
  150. $out[] = $row;
  151. }
  152. $this->free_result($query_id);
  153. return $out;
  154. }
  155. #-#fetch_array()
  156. #-#############################################
  157. # desc: does an update query with an array
  158. # param: table, assoc array with data (not escaped), where condition (optional. if none given, all records updated)
  159. # returns: (query_id) for fetching results etc
  160. public function update($table, $data, $where = '1')
  161. {
  162. $q = "UPDATE `$table` SET ";
  163. foreach ($data as $key => $val) {
  164. if (strtolower($val) == 'null') $q .= "`$key` = NULL, ";
  165. elseif (strtolower($val) == 'now()') $q .= "`$key` = NOW(), ";
  166. elseif (preg_match("/^increment\((\-?\d+)\)$/i", $val, $m)) $q .= "`$key` = `$key` + $m[1], ";
  167. else $q .= "`$key`='" . $this->escape($val) . "', ";
  168. }
  169. $q = rtrim($q, ', ') . ' WHERE ' . $where . ';';
  170. return $this->query($q);
  171. }
  172. #-#update()
  173. #-#############################################
  174. # desc: does an insert query with an array
  175. # param: table, assoc array with data (not escaped)
  176. # returns: id of inserted record, false if error
  177. public function insert($table, $data)
  178. {
  179. $q = "INSERT INTO `$table` ";
  180. $v = '';
  181. $n = '';
  182. foreach ($data as $key => $val) {
  183. $n .= "`$key`, ";
  184. if (strtolower($val) == 'null') $v .= "NULL, ";
  185. elseif (strtolower($val) == 'now()') $v .= "NOW(), ";
  186. else $v .= "'" . $this->escape($val) . "', ";
  187. }
  188. $q .= "(" . rtrim($n, ', ') . ") VALUES (" . rtrim($v, ', ') . ");";
  189. if ($this->query($q)) {
  190. return mysql_insert_id($this->link_id);
  191. }
  192. else return false;
  193. }
  194. #-#insert()
  195. #-#############################################
  196. # desc: does an insert query with an array
  197. # param: table, assoc array with data (not escaped)
  198. # returns: id of inserted record, false if error
  199. public function insert_or_update($table, $insertData, $updateData){
  200. $n='';
  201. $v='';
  202. $u = array();
  203. $uVal='';
  204. foreach($insertData as $key=>$val){
  205. $n.="`$key`, ";
  206. if(strtolower($val)=='null') $v.="NULL, ";
  207. elseif(strtolower($val)=='now()') $v.="NOW(), ";
  208. else $v.= "'".$this->escape($val)."', ";
  209. }
  210. foreach($updateData as $key=>$val)
  211. {
  212. if(strtolower($val)=='null')
  213. {
  214. $uVal = "NULL";
  215. }
  216. elseif(strtolower($val)=='now()'){
  217. $uVal = "NOW()";
  218. }
  219. else
  220. {
  221. $uVal = "'".$this->escape($val)."'";
  222. }
  223. array_push($u, "`$key`=".$uVal);
  224. }
  225. $q = "INSERT INTO `$table` (". rtrim($n, ', ') .") VALUES (". rtrim($v, ', ') .") ON DUPLICATE KEY UPDATE ".join(', ',$u).";";
  226. if($this->query($q)){
  227. return mysql_insert_id($this->link_id);
  228. }
  229. else return false;
  230. }#-#insert()
  231. #-#############################################
  232. # desc: frees the resultset
  233. # param: query_id for mysql run. if none specified, last used
  234. private function free_result($query_id = -1)
  235. {
  236. if ($query_id != -1) {
  237. $this->query_id = $query_id;
  238. }
  239. if ($this->query_id != 0 && !@mysql_free_result($this->query_id)) {
  240. $this->oops("Result ID: <b>$this->query_id</b> could not be freed.");
  241. }
  242. }
  243. #-#free_result()
  244. #-#############################################
  245. # desc: throw an error message
  246. # param: [optional] any custom error to display
  247. private function oops($msg = '')
  248. {
  249. if (!empty($this->link_id)) {
  250. $this->error = mysql_error($this->link_id);
  251. $this->errno = mysql_errno($this->link_id);
  252. }
  253. else {
  254. $this->error = mysql_error();
  255. $this->errno = mysql_errno($this->link_id);
  256. $msg = "<b>WARNING:</b> No link_id found. Likely not be connected to database.<br />$msg";
  257. }
  258. // if no debug, done here
  259. if (!$this->debug) return;
  260. ?>
  261. <table align="center" border="1" cellspacing="0"
  262. style="background:white;color:black;width:80%;">
  263. <tr>
  264. <th colspan=2>Database Error</th>
  265. </tr>
  266. <tr>
  267. <td align="right" valign="top">Message:</td>
  268. <td><?php echo $msg; ?></td>
  269. </tr>
  270. <?php if (!empty($this->error)) echo '<tr><td align="right" valign="top" nowrap>MySQL Error:</td><td>' . $this->error . '</td></tr>'; ?>
  271. <tr>
  272. <td align="right">Date:</td>
  273. <td><?php echo date("l, F j, Y \a\\t g:i:s A"); ?></td>
  274. </tr>
  275. <?php if (!empty($_SERVER['REQUEST_URI'])) echo '<tr><td align="right">Script:</td><td><a href="' . $_SERVER['REQUEST_URI'] . '">' . $_SERVER['REQUEST_URI'] . '</a></td></tr>'; ?>
  276. <?php if (!empty($_SERVER['HTTP_REFERER'])) echo '<tr><td align="right">Referer:</td><td><a href="' . $_SERVER['HTTP_REFERER'] . '">' . $_SERVER['HTTP_REFERER'] . '</a></td></tr>'; ?>
  277. </table>
  278. <?php
  279. }
  280. #-#oops()
  281. }
  282. //CLASS Database
  283. ###################################################################################################
  284. ?>