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

/eapInc/Database.php

https://github.com/durand54/caresite
PHP | 395 lines | 195 code | 55 blank | 145 comment | 36 complexity | cc66ce409ada4c0cb8c43013d9b7ba5c MD5 | raw file
  1. <?php
  2. /**
  3. * Database
  4. * Provides an interface to a MySQL database.
  5. *
  6. * @author Travis Dent <tcdent@gmail.com>
  7. * @copyright (c) 2007-2008 Travis Dent. All rights reserved.
  8. * @package Framework
  9. * @version 0.3.3
  10. */
  11. class Database {
  12. /**
  13. * @var string Prefix to prepend to table names in all queries.
  14. */
  15. public $prefix;
  16. /**
  17. * @var array Holds SQL statements from all executed queries.
  18. */
  19. public $queries = array();
  20. /**
  21. * @var mixed MySQL connection instance.
  22. */
  23. public $connection;
  24. /**
  25. * @var mixed MySQL database instance.
  26. */
  27. public $database;
  28. public function __construct($config=NULL){
  29. if($config == NULL){
  30. $config = $_ENV['CONFIG']['db'];
  31. }
  32. $this->connect($config['host'], $config['user'], $config['password'], $config['name']);
  33. if(array_key_exists('prefix', $config)) $this->prefix = $config['prefix'];
  34. }
  35. /**
  36. * Open a connection.
  37. *
  38. * @param string $host Database hostname.
  39. * @param string $user Database username.
  40. * @param string $password Database password.
  41. * @param string $database Database name.
  42. */
  43. public function connect($host, $user, $password, $database){
  44. if(!$this->connection = mysql_connect($host, $user, $password)){
  45. die("Could not connect to server: ".mysql_error());
  46. }
  47. elseif(!$this->database = mysql_select_db($database, $this->connection)){
  48. die("Could not select database: ".mysql_error());
  49. }
  50. return TRUE;
  51. }
  52. /**
  53. * Report an error with a query.
  54. *
  55. * @param string $query Query that caused an error.
  56. * @global mixed $errors Instance of Error class.
  57. */
  58. public function error($query){
  59. global $errors;
  60. $message = "There was an error retrieving your request. The query has been printed below.<br />\n";
  61. $message .= "<p style=\"font-family:monospace;\">$query</p>";
  62. if($errors){
  63. $errors->warn($message);
  64. }
  65. else {
  66. print $message;
  67. }
  68. }
  69. /**
  70. * Store and execute an SQL query.
  71. *
  72. * @param string $query Query to execute.
  73. * @return mixed Query result.
  74. */
  75. public function query($query){
  76. //log_message("[Database] Query: $query");
  77. //$this->queries[] = $query;
  78. return mysql_query($query);
  79. }
  80. /**
  81. * Run a fetch query with raw SQL.
  82. * Optionally, return with an array key other than the 'id'.
  83. *
  84. * @param string $query SQL query.
  85. * @param string $index Return the array with this column as the array key.
  86. * @return array Resulting rows.
  87. */
  88. public function get($query, $index=NULL){
  89. $query_result = $this->query($query);
  90. $num_rows = @mysql_num_rows($query_result);
  91. if($num_rows > 0){
  92. while($row = mysql_fetch_array($query_result, MYSQL_ASSOC)){
  93. if(array_key_exists($index, $row)){
  94. foreach(array_keys($row) as $key){
  95. if(count(array_keys($row)) == 2){
  96. $results[$row[$index]] = $this->un_clean($row[$key]);
  97. }
  98. elseif($key != $index){
  99. $results[$row[$index]][$key] = $this->un_clean($row[$key]);
  100. }
  101. }
  102. }
  103. else{
  104. $results[] = $row;
  105. }
  106. }
  107. return $results;
  108. }
  109. elseif($num_rows == 0){
  110. return FALSE;
  111. }
  112. else {
  113. $this->error($query);
  114. return FALSE;
  115. }
  116. }
  117. /**
  118. * Get all rows in a table.
  119. * Optionally, limit the result to a range, sort it, or return with an array key other than the 'id'.
  120. *
  121. * @param string $table Table to SELECT from.
  122. * @param string $start Entry to start with.
  123. * @param string $limit Number of entries to return.
  124. * @param string $order Order by a key using standard SQL syntax ex: "date ASC".
  125. * @param string $index Return the array with this column as the array key.
  126. * @return array Resulting rows.
  127. */
  128. public function get_all($table, $start=NULL, $limit=NULL, $order=NULL, $index=NULL){
  129. $query = "SELECT * FROM ".$this->prefix($table);
  130. if($order != NULL){
  131. $query .= " ORDER BY $order";
  132. }
  133. if($start > 0 || $limit > 0){
  134. $query .= " LIMIT $start, $limit";
  135. }
  136. if(!$return = $this->get($query, $index)){
  137. return array();
  138. }
  139. return $return;
  140. }
  141. /**
  142. * Get the first matching row in a table with raw SQL.
  143. *
  144. * @param string $query SQL query.
  145. * @return array Resulting rows or FALSE.
  146. */
  147. public function get_first($query){
  148. $query_result = $this->query($query);
  149. $num_rows = @mysql_num_rows($query_result);
  150. if($num_rows > 0){
  151. $result = mysql_fetch_array($query_result, MYSQL_ASSOC);
  152. foreach($result as $key => $value){
  153. $return[$key] = $this->un_clean($value);
  154. }
  155. return $return;
  156. }
  157. elseif($num_rows == 0){
  158. return FALSE;
  159. }
  160. else {
  161. $this->error($query);
  162. return FALSE;
  163. }
  164. }
  165. /**
  166. * Get the first row in a table with a $key matching $value.
  167. * Optionally, return with an array key other than the 'id'.
  168. *
  169. * @param string $table Table to SELECT from.
  170. * @param string $index Return the array with this column as the array key.
  171. * @return array Resulting rows.
  172. */
  173. public function get_by_key($key, $value, $table){
  174. return $this->get_first(sprintf(
  175. "SELECT * FROM %s WHERE %s = '%s'",
  176. $this->prefix($table),
  177. $this->clean($key),
  178. $this->clean($value)));
  179. }
  180. /**
  181. * Get a row in the table by its 'id'.
  182. *
  183. * @param string $id 'id' of the row to fetch.
  184. * @param string $table Table to SELECT from.
  185. * @return array Resulting rows.
  186. */
  187. public function get_by_id($id, $table){
  188. return $this->get_by_key('id', $id, $table);
  189. }
  190. /**
  191. * Count the rows in a table.
  192. * Optionally, restrict with a WHERE statement.
  193. *
  194. * @param string $table Table to count.
  195. * @param string $where Optional WHERE statement.
  196. * @return int Number of rows.
  197. */
  198. public function count($table, $where=NULL){
  199. $query = "SELECT count(*) as count FROM ".$this->prefix($table);
  200. if($where) $query .= " WHERE $where";
  201. if($result = $this->get_first($query)){
  202. return $result['count'];
  203. }
  204. return 0;
  205. }
  206. /**
  207. * UPDATE or INSERT a row.
  208. * If an index is passed the entry will be updated, otherwise it will be created.
  209. *
  210. * @param array $entry Associative array containing the entry to be saved.
  211. * @param string $table Table to update.
  212. * @param string $index Use this as the index. Use caution if you change this as multiple entries can be updated at once.
  213. * @return mixed 'id' of the inserted or updated entry or FALSE.
  214. */
  215. public function save($entry, $table, $index='id'){
  216. $table = $this->prefix($table);
  217. $values = "";
  218. $sep = "";
  219. foreach($entry as $key => $value){
  220. $values .= $sep . "`" . $key . "` = '" . $this->clean($value) . "'";
  221. $sep = ", ";
  222. }
  223. if($this->get_by_key($index, $entry[$index], $table)){
  224. //Updating existing.
  225. $query = "UPDATE $table SET $values WHERE $index = '".$entry[$index]."'";
  226. if($this->query($query)){
  227. return $entry[$index];
  228. }
  229. else {
  230. $this->error($query);
  231. return FALSE;
  232. }
  233. }
  234. else {
  235. //Adding new.
  236. $query = "INSERT INTO $table SET $values";
  237. if($this->query($query)){
  238. return mysql_insert_id();
  239. }
  240. else {
  241. $this->error($query);
  242. return FALSE;
  243. }
  244. }
  245. }
  246. /**
  247. * UPDATE or INSERT a row.
  248. * If an index is passed the entry will be updated, otherwise it will be created.
  249. *
  250. * @param array $entry Associative array containing the entry to be saved.
  251. * @param string $table Table to update.
  252. * @param string $index Use this as the index. Use caution if you change this as multiple entries can be updated at once.
  253. * @return mixed 'id' of the inserted or updated entry or FALSE.
  254. */
  255. public function saveComment($entry, $table, $index='id', $subscriber='subscriber',$date='date'){
  256. $table = $this->prefix($table);
  257. $values = "";
  258. $sep = "";
  259. foreach($entry as $key => $value){
  260. $values .= $sep . "`" . $key . "` = '" . $this->clean($value) . "'";
  261. $sep = ", ";
  262. }
  263. if($this->get_by_key($index, $entry[$index], $entry[$subscriber],$entry[$date], $table)){
  264. //Updating existing.
  265. $query = "UPDATE $table SET $values WHERE $index = '".$entry[$index]."' AND $subscriber = '".$entry[$subscriber]."' AND $date = '".$entry[$date]."'";
  266. if($this->query($query)){
  267. return $entry[$index];
  268. }
  269. else {
  270. $this->error($query);
  271. return FALSE;
  272. }
  273. }
  274. else {
  275. //Adding new.
  276. $query = "INSERT INTO $table SET $values";
  277. if($this->query($query)){
  278. return mysql_insert_id();
  279. }
  280. else {
  281. $this->error($query);
  282. return FALSE;
  283. }
  284. }
  285. }
  286. /**
  287. * DELETE a row.
  288. *
  289. * @param string $value Delete the row with this value for the $index.
  290. * @param string $table Table to update.
  291. * @param string $index Use this as the index. Use caution if you change this as multiple entries can be deleted at once.
  292. * @return mixed Query result.
  293. */
  294. public function delete($value, $table, $index='id'){
  295. return $this->query("DELETE FROM ".$this->prefix($table)." WHERE $index = '$value'");
  296. }
  297. public function delete_set($value, $table, $index='id'){
  298. return $this->query("DELETE FROM ".$this->prefix($table)." WHERE $index IS NULL");
  299. }
  300. /**
  301. * Prepend the prefix to the $table if one has been given.
  302. *
  303. * @param string $table Table to prefix.
  304. * @return string Prefixed table name.
  305. */
  306. public function prefix($table){
  307. if(!empty($this->prefix)){
  308. return $this->prefix.$table;
  309. }
  310. return $table;
  311. }
  312. /**
  313. * The current time in MySQL datetime format.
  314. *
  315. * @param string $format Date format.
  316. * @return string Formatted datetime.
  317. */
  318. public function now($format='Y-m-d H:i:s'){
  319. return date($format, time());
  320. }
  321. /**
  322. * Return a MySQL friendly string.
  323. *
  324. * @param string $string Value to clean.
  325. * @return string Cleaned value.
  326. */
  327. public function clean($string){
  328. return mysql_real_escape_string($string);
  329. }
  330. /**
  331. * Return the 'cleaned' value in its original state.
  332. *
  333. * @param string $string Value to un-clean.
  334. * @return string Un-cleaned value.
  335. */
  336. public function un_clean($string){
  337. return stripslashes($string);
  338. }
  339. }
  340. ?>