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

/web/lib/Database.singleton.php

https://code.google.com/p/gctour/
PHP | 310 lines | 156 code | 70 blank | 84 comment | 30 complexity | 3e99a9bd00facd73bbc98952bd2c2599 MD5 | raw file
  1. <?php
  2. # Name: Database.singleton.php
  3. # File Description: MySQL Singleton Class to allow easy and clean access to common mysql commands
  4. # Author: ricocheting
  5. # Web: http://www.ricocheting.com/
  6. # Update: 2010-07-19
  7. # Version: 3.1.4
  8. # Copyright 2003 ricocheting.com
  9. /*
  10. This program is free software: you can redistribute it and/or modify
  11. it under the terms of the GNU General Public License as published by
  12. the Free Software Foundation, either version 3 of the License, or
  13. (at your option) any later version.
  14. This program is distributed in the hope that it will be useful,
  15. but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. GNU General Public License for more details.
  18. You should have received a copy of the GNU General Public License
  19. along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. */
  21. //require("config.inc.php");
  22. //$db = Database::obtain(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
  23. //$db = Database::obtain();
  24. ###################################################################################################
  25. ###################################################################################################
  26. ###################################################################################################
  27. class Database{
  28. // debug flag for showing error messages
  29. public $debug = true;
  30. // Store the single instance of Database
  31. private static $instance;
  32. private $server = ""; //database server
  33. private $user = ""; //database login name
  34. private $pass = ""; //database login password
  35. private $database = ""; //database name
  36. private $error = "";
  37. #######################
  38. //number of rows affected by SQL query
  39. public $affected_rows = 0;
  40. private $link_id = 0;
  41. private $query_id = 0;
  42. #-#############################################
  43. # desc: constructor
  44. private function __construct($server=null, $user=null, $pass=null, $database=null){
  45. // error catching if not passed in
  46. if($server==null || $user==null || $database==null){
  47. $this->oops("Database information must be passed in when the object is first created.");
  48. }
  49. $this->server=$server;
  50. $this->user=$user;
  51. $this->pass=$pass;
  52. $this->database=$database;
  53. }#-#constructor()
  54. #-#############################################
  55. # desc: singleton declaration
  56. public static function obtain($server=null, $user=null, $pass=null, $database=null){
  57. if (!self::$instance){
  58. self::$instance = new Database($server, $user, $pass, $database);
  59. }
  60. return self::$instance;
  61. }#-#obtain()
  62. #-#############################################
  63. # desc: connect and select database using vars above
  64. # Param: $new_link can force connect() to open a new link, even if mysql_connect() was called before with the same parameters
  65. public function connect($new_link=false){
  66. $this->link_id=@mysql_connect($this->server,$this->user,$this->pass,$new_link);
  67. if (!$this->link_id){//open failed
  68. $this->oops("Could not connect to server: <b>$this->server</b>.");
  69. }
  70. if(!@mysql_select_db($this->database, $this->link_id)){//no database
  71. $this->oops("Could not open database: <b>$this->database</b>.");
  72. }
  73. // unset the data so it can't be dumped
  74. $this->server='';
  75. $this->user='';
  76. $this->pass='';
  77. $this->database='';
  78. }#-#connect()
  79. #-#############################################
  80. # desc: close the connection
  81. public function close(){
  82. if(!@mysql_close($this->link_id)){
  83. $this->oops("Connection close failed.");
  84. }
  85. }#-#close()
  86. #-#############################################
  87. # Desc: escapes characters to be mysql ready
  88. # Param: string
  89. # returns: string
  90. public function escape($string){
  91. if(get_magic_quotes_runtime()) $string = stripslashes($string);
  92. return @mysql_real_escape_string($string,$this->link_id);
  93. }#-#escape()
  94. #-#############################################
  95. # Desc: executes SQL query to an open connection
  96. # Param: (MySQL query) to execute
  97. # returns: (query_id) for fetching results etc
  98. public function query($sql){
  99. // do query
  100. $this->query_id = @mysql_query($sql, $this->link_id);
  101. if (!$this->query_id){
  102. $this->oops("<b>MySQL Query fail:</b> $sql");
  103. return 0;
  104. }
  105. $this->affected_rows = @mysql_affected_rows($this->link_id);
  106. return $this->query_id;
  107. }#-#query()
  108. #-#############################################
  109. # desc: does a query, fetches the first row only, frees resultset
  110. # param: (MySQL query) the query to run on server
  111. # returns: array of fetched results
  112. public function query_first($query_string){
  113. $query_id = $this->query($query_string);
  114. $out = $this->fetch($query_id);
  115. $this->free_result($query_id);
  116. return $out;
  117. }#-#query_first()
  118. #-#############################################
  119. # desc: fetches and returns results one line at a time
  120. # param: query_id for mysql run. if none specified, last used
  121. # return: (array) fetched record(s)
  122. public function fetch($query_id=-1){
  123. // retrieve row
  124. if ($query_id!=-1){
  125. $this->query_id=$query_id;
  126. }
  127. if (isset($this->query_id)){
  128. $record = @mysql_fetch_assoc($this->query_id);
  129. }else{
  130. $this->oops("Invalid query_id: <b>$this->query_id</b>. Records could not be fetched.");
  131. }
  132. return $record;
  133. }#-#fetch()
  134. #-#############################################
  135. # desc: returns all the results (not one row)
  136. # param: (MySQL query) the query to run on server
  137. # returns: assoc array of ALL fetched results
  138. public function fetch_array($sql){
  139. $query_id = $this->query($sql);
  140. $out = array();
  141. while ($row = $this->fetch($query_id)){
  142. $out[] = $row;
  143. }
  144. $this->free_result($query_id);
  145. return $out;
  146. }#-#fetch_array()
  147. #-#############################################
  148. # desc: does an update query with an array
  149. # param: table, assoc array with data (not escaped), where condition (optional. if none given, all records updated)
  150. # returns: (query_id) for fetching results etc
  151. public function update($table, $data, $where='1'){
  152. $q="UPDATE `$table` SET ";
  153. foreach($data as $key=>$val){
  154. if(strtolower($val)=='null') $q.= "`$key` = NULL, ";
  155. elseif(strtolower($val)=='now()') $q.= "`$key` = NOW(), ";
  156. elseif(preg_match("/^increment\((\-?\d+)\)$/i",$val,$m)) $q.= "`$key` = `$key` + $m[1], ";
  157. else $q.= "`$key`='".$this->escape($val)."', ";
  158. }
  159. $q = rtrim($q, ', ') . ' WHERE '.$where.';';
  160. return $this->query($q);
  161. }#-#update()
  162. #-#############################################
  163. # desc: does an replace query with an array
  164. # param: table, assoc array with data (not escaped)
  165. # returns: id of inserted record, false if error
  166. public function replace($table, $data){
  167. $q="REPLACE INTO `$table` ";
  168. $v=''; $n='';
  169. foreach($data as $key=>$val){
  170. $n.="`$key`, ";
  171. if(strtolower($val)=='null') $v.="NULL, ";
  172. elseif(strtolower($val)=='now()') $v.="NOW(), ";
  173. elseif(preg_match("/^increment\((\-?\d+)\)$/i",$val,$m)) $q.= "`$key` = `$key` + $m[1], ";
  174. else $v.= "'".$this->escape($val)."', ";
  175. }
  176. $q .= "(". rtrim($n, ', ') .") VALUES (". rtrim($v, ', ') .");";
  177. if($this->query($q)){
  178. return mysql_insert_id($this->link_id);
  179. }
  180. else return false;
  181. }#-#replace()
  182. #-#############################################
  183. # desc: does an insert query with an array
  184. # param: table, assoc array with data (not escaped)
  185. # returns: id of inserted record, false if error
  186. public function insert($table, $data){
  187. $q="INSERT INTO `$table` ";
  188. $v=''; $n='';
  189. foreach($data as $key=>$val){
  190. $n.="`$key`, ";
  191. if(strtolower($val)=='null') $v.="NULL, ";
  192. elseif(strtolower($val)=='now()') $v.="NOW(), ";
  193. else $v.= "'".$this->escape($val)."', ";
  194. }
  195. $q .= "(". rtrim($n, ', ') .") VALUES (". rtrim($v, ', ') .");";
  196. if($this->query($q)){
  197. return mysql_insert_id($this->link_id);
  198. }
  199. else return false;
  200. }#-#insert()
  201. #-#############################################
  202. # desc: frees the resultset
  203. # param: query_id for mysql run. if none specified, last used
  204. private function free_result($query_id=-1){
  205. if ($query_id!=-1){
  206. $this->query_id=$query_id;
  207. }
  208. if($this->query_id!=0 && !@mysql_free_result($this->query_id)){
  209. $this->oops("Result ID: <b>$this->query_id</b> could not be freed.");
  210. }
  211. }#-#free_result()
  212. #-#############################################
  213. # desc: throw an error message
  214. # param: [optional] any custom error to display
  215. private function oops($msg=''){
  216. if(!empty($this->link_id)){
  217. $this->error = mysql_error($this->link_id);
  218. }
  219. else{
  220. $this->error = mysql_error();
  221. $msg="<b>WARNING:</b> No link_id found. Likely not be connected to database.<br />$msg";
  222. }
  223. // if no debug, done here
  224. if(!$this->debug) return;
  225. ?>
  226. <table align="center" border="1" cellspacing="0" style="background:white;color:black;width:80%;">
  227. <tr><th colspan=2>Database Error</th></tr>
  228. <tr><td align="right" valign="top">Message:</td><td><?php echo $msg; ?></td></tr>
  229. <?php if(!empty($this->error)) echo '<tr><td align="right" valign="top" nowrap>MySQL Error:</td><td>'.$this->error.'</td></tr>'; ?>
  230. <tr><td align="right">Date:</td><td><?php echo date("l, F j, Y \a\\t g:i:s A"); ?></td></tr>
  231. <?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>'; ?>
  232. <?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>'; ?>
  233. </table>
  234. <?php
  235. }#-#oops()
  236. }//CLASS Database
  237. ###################################################################################################
  238. ?>