PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/db.php

https://github.com/dreamhackcrew/API
PHP | 463 lines | 260 code | 71 blank | 132 comment | 46 complexity | bc9251940d2a16d88316e85571fa9f94 MD5 | raw file
  1. <?php
  2. require_once('config.php');
  3. function db(){
  4. return db::getInstance();
  5. }
  6. class db {
  7. const version = '3.0.0';
  8. const database = 'mysql';
  9. public $_db;
  10. private $tables = array();
  11. protected static $instance = null;
  12. private $_mysqli = null;
  13. private $prefix=null;
  14. private $repaircount = 0;
  15. // __construct {{{
  16. /**
  17. * Initiate database connect
  18. *
  19. */
  20. public function __construct()
  21. {
  22. //register_shutdown_function('session_write_close');
  23. }
  24. // }}}
  25. function __destruct(){
  26. //if($this->_mysqli)
  27. // $this->_mysqli->close();
  28. }
  29. function ping() {
  30. if($this->_mysqli)
  31. return $this->_mysqli->ping();
  32. return false;
  33. }
  34. function connect($server,$user,$password,$database){
  35. $this->_mysqli = mysqli_init();
  36. if(!$this->_mysqli->real_connect($server, $user, $password,$database)){
  37. $this->_mysqli = null;
  38. return !trigger_error('Broken connection to database server: '.$server."<br/>\n".mysqli_connect_error().' Code:'.mysqli_connect_errno(),E_USER_WARNING);
  39. }
  40. $this->scanTables();
  41. /* change character set to utf8 */
  42. if (!$this->_mysqli->set_charset("utf8"))
  43. trigger_error('Error setting charset to utf8!',E_USER_WARNING);
  44. }
  45. public static function getInstance($AutoCreate=false) {// {{{
  46. if($AutoCreate===true && !self::$instance) {
  47. self::init();
  48. }
  49. return self::$instance;
  50. }
  51. // }}}
  52. public function setPrefix($p) {// {{{
  53. $this->prefix = $p;
  54. }
  55. // }}}
  56. public function getPrefix() {// {{{
  57. return $this->prefix;
  58. }
  59. // }}}
  60. public static function init() {// {{{
  61. return self::$instance = new self();
  62. }
  63. // }}}
  64. // scanTables {{{
  65. private function scanTables()
  66. {
  67. //if(!$this->tables)
  68. if ( $tables = $this->fetchAllOne("SHOW tables") )
  69. foreach( $tables as $table ){
  70. /* THIS IS TO SLOW TO USE
  71. $tmp = array();
  72. $fields = $this->fetchAll("SHOW FIELDS FROM `".$table."`");
  73. foreach($fields AS $field){
  74. $tmp[] = $field['Field'];
  75. }
  76. */
  77. $this->$table = $table ;
  78. }
  79. return true;
  80. }
  81. // }}}
  82. // escapeStr {{{
  83. /**
  84. * Perform mysql_real_escape_string on $args
  85. * Returns escaped (string|array)
  86. *
  87. * @param (string|array) $str, array or string
  88. */
  89. public function escapeStr($str)
  90. {
  91. if(!$this->_mysqli)
  92. return !trigger_error('php-mysqli is not installed',E_USER_ERROR);
  93. $strip = get_magic_quotes_gpc();
  94. if(is_array($str)) { // if array do loop
  95. foreach($str as $key => $val) {
  96. if ($strip)
  97. $val = stripslashes($val);
  98. $str[$key] =$this->_mysqli->real_escape_string($val);
  99. }
  100. } else { // else just escape the string.
  101. if ($strip)
  102. $str = stripslashes($str);
  103. $str = $this->_mysqli->real_escape_string($str);
  104. }
  105. return $str;
  106. }
  107. // }}}
  108. // insertId {{{
  109. /**
  110. * A port of mysql_insert_id()
  111. *
  112. * @return int mysql_insert_id
  113. */
  114. public function insertId()
  115. {
  116. return $this->_mysqli->insert_id;
  117. }
  118. // }}}
  119. // query {{{
  120. /**
  121. * perform a database query
  122. *
  123. * @param string $sql the sql statement
  124. */
  125. public function query($sql)
  126. {
  127. if($this->_mysqli === null)
  128. return false;
  129. $orgsql = $sql;
  130. if ( trim($sql) == '' ){
  131. return !@trigger_error('Database query was emty!');
  132. }
  133. if ( func_num_args() > 1 ) {
  134. $args = array_slice(func_get_args(),1);
  135. $sql = vsprintf($sql,$this->escapeStr($args));
  136. }
  137. $sql = str_replace('##',$this->getPrefix(),$sql);
  138. if( !$q = $this->_mysqli->query($sql) ) {
  139. db()->insert(array(
  140. //'customer' => $this->request['oauth_consumer_key'],
  141. 'message' => 'SQL error: '.$this->_mysqli->error,
  142. 'data' => json_encode(array(
  143. 'query' => $orgsql,
  144. 'arguments' => $args,
  145. 'message' => $this->_mysqli->error,
  146. )),
  147. ),'api_messages');
  148. trigger_error('A database error have occurred, please contact your system administrator! ');
  149. echo $sql;
  150. echo $this->_mysqli->error;
  151. }
  152. return $q;
  153. }
  154. // }}}
  155. // fetchRow {{{
  156. /**
  157. * fetch one row with mysql_fetch_row
  158. * Returns array or false
  159. *
  160. */
  161. public function fetchRow($qryId = null)
  162. {
  163. if ($qryId != null)
  164. return ($r = $qryId->fetch_row() ) ? $r : false;
  165. return false;
  166. }
  167. // }}}
  168. // fetchAssoc {{{
  169. /**
  170. * Fetch one row with mysql_fetch_assoc
  171. * Returns associative array or false
  172. *
  173. */
  174. public function fetchAssoc($qryId = null)
  175. {
  176. if ($qryId)
  177. return ($r = $qryId->fetch_assoc() ) ? $r : false;
  178. return false;
  179. }
  180. // }}}
  181. // affectedRows {{{
  182. /**
  183. * do mysql_affected_rows
  184. *
  185. *
  186. */
  187. public function affectedRows()
  188. {
  189. return $this->_mysqli->affected_rows;
  190. }
  191. // }}}
  192. // numRows {{{
  193. /**
  194. * do mysql_num_rows
  195. *
  196. *
  197. */
  198. public function numRows()
  199. {
  200. $this->_mysqli->store_result();
  201. return $this->_mysqli->num_rows;
  202. }
  203. // }}}
  204. // fetchAll {{{
  205. /**
  206. * Perform query.
  207. * Return multidimensional array or false
  208. *
  209. * @param string $sql sql query string
  210. */
  211. public function fetchAll($sql = '')
  212. {
  213. if ( func_num_args() > 1 ) {
  214. $args = array_slice(func_get_args(),1);
  215. $args = $this->escapeStr($args);
  216. $sql = vsprintf($sql,$args);
  217. }
  218. $q = $this->query($sql);
  219. if ($q) {
  220. $r = array();
  221. while($result = $this->fetchAssoc($q) ) {
  222. $r[] = $result;
  223. }
  224. //mysql_free_result($q);
  225. $q->close();
  226. return (count($r) > 0) ? $r : false;
  227. } else {
  228. return false;
  229. }
  230. }
  231. // }}}
  232. // fetchSingle {{{
  233. /**
  234. * Perform query.
  235. * Return array or false
  236. *
  237. * @param string $sql sql query string
  238. */
  239. public function fetchSingle($sql = '')
  240. {
  241. if ( func_num_args() > 1 ) {
  242. $args = array_slice(func_get_args(),1);
  243. $args = $this->escapeStr($args);
  244. $sql = vsprintf($sql,$this->escapeStr($args));
  245. }
  246. if( $q = $this->query($sql) ) {
  247. if($r = $this->fetchAssoc($q)){
  248. //mysql_free_result($q);
  249. $q->close();
  250. return $r;
  251. }
  252. return array();
  253. }
  254. return false;
  255. }
  256. // }}}
  257. // fetchOne {{{
  258. /**
  259. * Perform query.
  260. * Return array or false
  261. *
  262. * @param string $sql sql query string
  263. */
  264. public function fetchOne($sql = '')
  265. {
  266. if ( func_num_args() > 1 ) {
  267. $args = array_slice(func_get_args(),1);
  268. $args = $this->escapeStr($args);
  269. $sql = vsprintf($sql,$this->escapeStr($args));
  270. }
  271. if ( $q = $this->query($sql) ) {
  272. if($r=$this->fetchRow($q)){
  273. //mysql_free_result($q);
  274. $q->close();
  275. return $r[0];
  276. }
  277. }
  278. return false;
  279. }
  280. // }}}
  281. // fetchAllOne {{{
  282. /**
  283. * Perform query.
  284. * Return array or false
  285. *
  286. * @param string $sql sql query string
  287. */
  288. public function fetchAllOne($sql = '')
  289. {
  290. if ( func_num_args() > 1 ) {
  291. $args = array_slice(func_get_args(),1);
  292. $args = $this->escapeStr($args);
  293. $sql = vsprintf($sql,$this->escapeStr($args));
  294. }
  295. $q = $this->query($sql);
  296. if ($q) {
  297. $r = array();
  298. while($result = $this->fetchRow($q) ) {
  299. $r[] = $result[0];
  300. }
  301. // mysql_free_result($q);
  302. $q->close();
  303. return (count($r) > 0) ? $r : false;
  304. } else {
  305. return false;
  306. }
  307. }
  308. // }}}
  309. // insert {{{
  310. /**
  311. * Return select sql statement
  312. *
  313. * @param array $fields fields to insert
  314. * @param string $table table to do insert on
  315. */
  316. public function insert($fields,$table)
  317. {
  318. if ( !is_array($fields) || count($fields)==0 )
  319. return !trigger_error('Can not insert a post without data in the database!',E_USER_WARNING);
  320. $table = $this->escapeStr($table);
  321. $sql = sprintf('INSERT INTO `%s` SET ',$table);
  322. foreach($fields as $key => $val) {
  323. $key = $this->escapeStr($key);
  324. $val = $this->escapeStr($val);
  325. if (!isset($notFirst)) {
  326. $notFirst = 'Y';
  327. } else $sql .= ', ';
  328. if (is_int($val)) {
  329. $sql .= sprintf('`%s` = %d', $key, intval($val) );
  330. } elseif (is_array($val)) {
  331. $sql .= sprintf('`%s` = %s', $key, $val['txt']);
  332. } elseif (is_string($val)) {
  333. $sql .= sprintf('`%s` = "%s"', $key, $val);
  334. } else {
  335. return false;
  336. }
  337. }
  338. if ( $q = $this->query($sql)) return ( $this->insertId() ? $this->insertId() : $q );
  339. return false;
  340. }
  341. // }}}
  342. // update {{{
  343. /**
  344. * Return select sql statement
  345. *
  346. * @param array $fields fields to insert
  347. * @param string $table table to do insert on
  348. */
  349. public function update($fields,$table,$where)
  350. {
  351. if ( !is_array($fields) || count($fields)==0 )
  352. return !trigger_error('Can not insert a post without data in the database!',E_USER_WARNING);
  353. $table = $this->escapeStr($table);
  354. $sql = sprintf('UPDATE `%s` SET ',$table);
  355. foreach($fields as $key => $val) {
  356. $key = $this->escapeStr($key);
  357. $val = $this->escapeStr($val);
  358. if (!isset($notFirst)) {
  359. $notFirst = 'Y';
  360. } else $sql .= ', ';
  361. if (is_int($val)) {
  362. $sql .= sprintf('`%s` = %d', $key, intval($val) );
  363. } elseif (is_array($val)) {
  364. $sql .= sprintf('`%s` = %s', $key, $val['txt']);
  365. } elseif (is_string($val)) {
  366. $sql .= sprintf('`%s` = "%s"', $key, $val);
  367. } else {
  368. return false;
  369. }
  370. }
  371. if ( func_num_args() > 3 ) {
  372. $args = array_slice(func_get_args(),3);
  373. $where = vsprintf($where,$this->escapeStr($args));
  374. }
  375. $sql .= " ".$where;
  376. if ( $q = $this->query($sql)) return ( $this->insertId() ? $this->insertId() : $q );
  377. return false;
  378. }
  379. // }}}
  380. // }}}
  381. public static function now(){// {{{
  382. //returns mysql NOW() format.
  383. return date("Y-m-d H:i:s");
  384. }
  385. // }}}
  386. public static function curdate(){// {{{
  387. //returns mysql CURDATE() format.
  388. return date("Y-m-d");
  389. }
  390. // }}}
  391. }
  392. ?>