PageRenderTime 53ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/classes/sm/smDatabase.class.php

http://github.com/madeinnordeste/PHP-Server-Monitor-Plus
PHP | 365 lines | 177 code | 66 blank | 122 comment | 34 complexity | c446e16bae48636ab71051c657fe4d5d MD5 | raw file
Possible License(s): GPL-3.0
  1. <?php
  2. /*
  3. * PHP Server Monitor v2.0.1
  4. * Monitor your servers with error notification
  5. * http://phpservermon.sourceforge.net/
  6. *
  7. * Copyright (c) 2008-2011 Pepijn Over (ipdope@users.sourceforge.net)
  8. *
  9. * This file is part of PHP Server Monitor.
  10. * PHP Server Monitor 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. *
  15. * PHP Server Monitor is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with PHP Server Monitor. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. class smDatabase {
  24. protected $debug = array();
  25. protected $last_inserted_id;
  26. protected $link;
  27. protected $num_rows_found;
  28. protected $num_rows_returned;
  29. function __construct() {
  30. // Initizale connection
  31. $this->link = mysql_connect(SM_DB_HOST, SM_DB_USER, SM_DB_PASS);
  32. if (!mysql_select_db(SM_DB_NAME, $this->link)) {
  33. trigger_error(mysql_errno() . ": " . mysql_error());
  34. }
  35. // Setting the utf collection
  36. mysql_query("SET NAMES utf8;", $this->getLink());
  37. mysql_query("SET CHARACTER SET 'utf8';", $this->getLink());
  38. }
  39. /**
  40. * Executes a query
  41. *
  42. * @param $sql string MySQL query
  43. * @return resource mysql resource
  44. */
  45. public function executeQuery($sql) {
  46. $result = mysql_query($sql, $this->getLink());
  47. if (mysql_error($this->getLink())) {
  48. trigger_error(mysql_errno($this->getLink()) . ': ' . mysql_error($this->getLink()));
  49. return false;
  50. }
  51. if (is_resource($result) && mysql_num_rows($result) > 0) {
  52. // Rows returned
  53. $this->num_rows_returned = mysql_num_rows($result);
  54. // Rows found
  55. $result_num_rows_found = $this->fetchResults(mysql_query('SELECT FOUND_ROWS();'));
  56. $this->num_rows_found = $result_num_rows_found[0]['FOUND_ROWS()'];
  57. }
  58. if (substr(strtolower(trim($sql)), 0, 6) == 'insert') {
  59. // we have an insert
  60. $this->last_inserted_id = mysql_insert_id($this->getLink());
  61. $result = $this->last_inserted_id;
  62. }
  63. return $result;
  64. }
  65. /**
  66. * Exectues query and fetches result
  67. *
  68. * @param $query string MySQL query
  69. * @return $result array
  70. */
  71. public function query($query) {
  72. // Execute query and process results
  73. $result_resource = $this->executeQuery($query);
  74. $result = $this->fetchResults($result_resource);
  75. return $result;
  76. }
  77. /**
  78. * Fetch results from a query
  79. *
  80. * @param resource $result result from a mysql query
  81. * @return array $array with results (multi-dimimensial) for more than one rows
  82. */
  83. public function fetchResults($result_query){
  84. if (!is_resource($result_query)) {
  85. return array();
  86. }
  87. $num_rows = mysql_num_rows($result_query);
  88. $result = array();
  89. while($record = mysql_fetch_assoc($result_query)) {
  90. $result[] = $record;
  91. }
  92. return $result;
  93. }
  94. /**
  95. * Performs a select on the given table and returns an multi dimensional associative array with results
  96. *
  97. * @param string $table tablename
  98. * @param mixed $where string or array with where data
  99. * @param array $fields array with fields to be retrieved. if empty all fields will be retrieved
  100. * @param string $limit limit. for example: 0,30
  101. * @param array $orderby fields for the orderby clause
  102. * @param string $direction ASC or DESC. Defaults to ASC
  103. * @return array multi dimensional array with results
  104. */
  105. public function select($table, $where = null, $fields = null, $limit = '', $orderby = null, $direction = 'ASC'){
  106. // build query
  107. $query_parts = array();
  108. $query_parts[] = 'SELECT SQL_CALC_FOUND_ROWS';
  109. // Fields
  110. if ($fields !== null && !empty($fields)) {
  111. $query_parts[] = "`".implode('`,`', $fields)."`";
  112. } else {
  113. $query_parts[] = ' * ';
  114. }
  115. // From
  116. $query_parts[] = "FROM `{$table}`";
  117. // Where clause
  118. $query_parts[] = $this->buildWhereClause($table, $where);
  119. // Order by
  120. if ($orderby !== null && !empty($orderby)) {
  121. $orderby_clause = 'ORDER BY ';
  122. foreach($orderby as $field) {
  123. $orderby_clause .= "`{$field}`, ";
  124. }
  125. $query_parts[] = substr($orderby_clause, 0, -2) . ' ' . $direction;
  126. }
  127. // Limit
  128. if ($limit != '') {
  129. $query_parts[] = 'LIMIT ' . $limit;
  130. }
  131. $query = implode(' ', $query_parts);
  132. // Get results
  133. $result = $this->query($query);
  134. return $result;
  135. }
  136. public function selectRow($table, $where = null, $fields = null, $limit = '', $orderby = null, $direction = 'ASC') {
  137. $result = $this->select($table, $where, $fields, $limit, $orderby, $direction);
  138. if ($this->getNumRowsReturned() == '1') {
  139. $result = $result[0];
  140. }
  141. return $result;
  142. }
  143. /**
  144. * Remove a record from database
  145. *
  146. * @param string $table tablename
  147. * @param mixed $where Where clause array or primary Id (string) or where clause (string)
  148. * @return boolean
  149. */
  150. public function delete($table, $where = null){
  151. if ($table != '') {
  152. $sql = 'DELETE FROM `'.$table.'` ' . $this->buildWhereClause($table, $where);
  153. $this->query($sql);
  154. }
  155. }
  156. /**
  157. * Insert or update data to the database
  158. *
  159. * @param array $table table name
  160. * @param array $data data to save or insert
  161. * @param mixed $where either string ('user_id=2' or just '2' (works only with primary field)) or array with where clause (only when updating)
  162. */
  163. public function save($table, $data, $where = null) {
  164. if ($where === null) {
  165. // insert mode
  166. $query = "INSERT INTO ";
  167. } else {
  168. $query = "UPDATE ";
  169. }
  170. $query .= "`{$table}` SET ";
  171. foreach($data as $field => $value) {
  172. $value = $this->escapeValue($value);
  173. $query .= "`{$table}`.`{$field}`='{$value}', ";
  174. }
  175. $query = substr($query, 0, -2) . ' ' . $this->buildWhereClause($table, $where);
  176. return $this->query($query);
  177. }
  178. /**
  179. * Build WHERE clause for query
  180. *
  181. * @param string $table table name
  182. * @param mixed $where can be primary id (eg '2'), can be string (eg 'name=pepe') or can be array
  183. * @return string sql where clause
  184. */
  185. public function buildWhereClause($table, $where = null) {
  186. $query = '';
  187. if ($where !== null) {
  188. if (is_array($where)) {
  189. $query .= " WHERE ";
  190. foreach($where as $field => $value) {
  191. $value = $this->escapeValue($value);
  192. $query .= "`{$table}`.`{$field}`='{$value}' AND ";
  193. }
  194. $query = substr($query, 0, -5);
  195. } else {
  196. if (strpos($where, '=') === false) {
  197. // no field given, use primary field
  198. $structure = $this->getTableStructure($table);
  199. $where = $this->escapeValue($where);
  200. $query .= " WHERE `{$table}`.`{$structure['primary']}`='{$where}'";
  201. } elseif (strpos(strtolower(trim($where)), 'where') === false) {
  202. $query .= " WHERE {$where}";
  203. } else {
  204. $query .= ' '.$where;
  205. }
  206. }
  207. }
  208. return $query;
  209. }
  210. /**
  211. * Get table structure and primary key
  212. *
  213. * @param string $table table name
  214. * @return array primary key and database structure
  215. */
  216. public function getTableStructure($table) {
  217. if ($table == '') return false;
  218. $structure = $this->query("DESCRIBE `{$table}`");
  219. if (empty($structure)) return false;
  220. // use arrray search function to get primary key
  221. $search_needle = array(
  222. 'key' => 'Key',
  223. 'value' => 'PRI'
  224. );
  225. $primary = pep_array_search_key_value(
  226. $structure,
  227. array(
  228. 'key' => 'Key',
  229. 'value' => 'PRI'
  230. )
  231. );
  232. $primary_field = $structure[$primary[0]['path'][0]]['Field'];
  233. return array(
  234. 'primary' => $primary_field,
  235. 'fields' => $structure
  236. );
  237. }
  238. /**
  239. * Get information about a field from the database
  240. *
  241. * @param string $table
  242. * @param string $field
  243. * @return array mysql field information
  244. */
  245. public function getFieldInfo($table, $field) {
  246. if ($table == '' || $field == '') return array();
  247. $db_structure = $this->getTableStructure($table);
  248. $field_info = pep_array_search_key_value(
  249. $db_structure,
  250. array(
  251. 'key' => 'Field',
  252. 'value' => $field
  253. )
  254. );
  255. if (empty($field_info)) {
  256. return array();
  257. }
  258. // return field info
  259. return $field_info[0]['result'];
  260. }
  261. /**
  262. * Formats the value for the SQL query to secure against injections
  263. *
  264. * @param string $value
  265. * @return string
  266. */
  267. public function escapeValue($value) {
  268. if(get_magic_quotes_gpc()) {
  269. $value = stripslashes($value);
  270. }
  271. $value = mysql_real_escape_string($value, $this->link);
  272. return $value;
  273. }
  274. /**
  275. * Get number of rows found
  276. *
  277. * @return int number of rows found
  278. */
  279. public function getNumRowsFound() {
  280. return $this->num_rows_found;
  281. }
  282. /**
  283. * Get number of rows returned
  284. *
  285. * @return int number of rows returned
  286. */
  287. public function getNumRowsReturned() {
  288. return $this->num_rows_returned;
  289. }
  290. /**
  291. * Get the database connection identifier
  292. *
  293. * @return object db connection
  294. */
  295. public function getLink() {
  296. return $this->link;
  297. }
  298. }
  299. ?>