database.php 973 B

12345678910111213141516171819202122232425262728293031323334353637
  1. <?php
  2. require_once(realpath(dirname(__FILE__)).'/config.php');
  3. function get_sql(){
  4. static $sql;
  5. if(is_null($sql)){
  6. $sql = new mysqli(get('host'),get('user'),get('password'),get('database'));
  7. if($sql && $sql->connect_errno){
  8. die("Failed to connect to MySQL: ".$sql->connect_error);
  9. }
  10. if(!$sql->autocommit(true)){
  11. die("Failed to connect to MySQL: ".$sql->connect_error);
  12. }
  13. }
  14. return $sql;
  15. }
  16. function query($query,$args=Array()){
  17. $sql = get_sql();
  18. for ($i=0;$i<count($args);$i++){
  19. if(is_string($args[$i])){
  20. $args[$i] = get_sql()->real_escape_string($args[$i]);
  21. }elseif(!is_numeric($args[$i])){
  22. return false;
  23. }
  24. }
  25. return get_sql()->query(vsprintf($query,$args));
  26. }
  27. function fetch_all($result,$type=MYSQLI_NUM){
  28. if(method_exists('mysqli_result', 'fetch_all')){
  29. $res = $result->fetch_all($type);
  30. }else{
  31. for($res = array(); $tmp = $result->fetch_array($type);){
  32. $res[] = $tmp;
  33. }
  34. }
  35. return $res;
  36. }
  37. ?>