Db.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. <?php
  2. namespace WY\app\libs;
  3. use WY\app\Config;
  4. use WY\app\libs\Log;
  5. use PDO;
  6. use PDOException;
  7. if (!defined('WY_ROOT')) {
  8. exit;
  9. }
  10. class Db
  11. {
  12. private $db = null;
  13. static $instance = null;
  14. function __construct()
  15. {
  16. }
  17. function getConfig()
  18. {
  19. return Config::db();
  20. }
  21. static function getInstance()
  22. {
  23. if (self::$instance == null) {
  24. self::$instance = new Db();
  25. }
  26. return self::$instance;
  27. }
  28. function connect()
  29. {
  30. try {
  31. $this->db = new PDO('mysql:host=' . $this->getConfig()['server'] . ';port=' . $this->getConfig()['port'] . ';dbname=' . $this->getConfig()['name'] . ';charset=utf8', $this->getConfig()['user'], $this->getConfig()['pass']);
  32. $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  33. } catch (PDOException $e) {
  34. if ($this->getConfig()['debug']) {
  35. Log::$type = 'mysql';
  36. Log::write($e->getMessage());
  37. }
  38. echo 'database connect error.';
  39. exit;
  40. }
  41. return $this->db;
  42. }
  43. function isConnected()
  44. {
  45. if ($this->db == null) {
  46. return false;
  47. }
  48. return true;
  49. }
  50. function prepare($sql)
  51. {
  52. $stm = $this->db->prepare($sql);
  53. return $stm;
  54. }
  55. function bindValue($stm, $params)
  56. {
  57. if (!$params) {
  58. return false;
  59. }
  60. foreach ($params as $key => $val) {
  61. $key++;
  62. $stm->bindValue($key, $val);
  63. }
  64. }
  65. function bindParam($stm, $params)
  66. {
  67. if (!$params) {
  68. return false;
  69. }
  70. foreach ($params as $key => $val) {
  71. $key++;
  72. $stm->bindParam($key, $val);
  73. }
  74. }
  75. function execute($stm)
  76. {
  77. try {
  78. $stm->execute();
  79. } catch (PDOException $e) {
  80. $trace = $e->getTrace();
  81. $str = '';
  82. foreach ($trace[2] as $key => $val) {
  83. if ($key == 'file' || $key == 'line' || $key == 'class') {
  84. $str .= $str ? "\n" : '';
  85. $str .= '[' . $key . ']' . $val;
  86. }
  87. }
  88. Log::write('error in ' . $e->getFile() . ' ' . $e->getLine() . "\n" . $e->getMessage() . "\n" . $stm->queryString . "\n" . $str);
  89. }
  90. }
  91. function query($sql)
  92. {
  93. try {
  94. return $this->db->query($sql);
  95. } catch (PDOException $e) {
  96. Log::write('error in ' . $e->getFile() . ' ' . $e->getLine() . "\n" . $e->getMessage() . "\n" . $stm->queryString);
  97. }
  98. }
  99. function exec($sql)
  100. {
  101. try {
  102. return $this->db->exec($sql);
  103. } catch (PDOException $e) {
  104. Log::write('error in ' . $e->getFile() . ' ' . $e->getLine() . "\n" . $e->getMessage() . "\n" . $stm->queryString);
  105. }
  106. }
  107. function fetchAll($stm)
  108. {
  109. return $stm->fetchAll(PDO::FETCH_ASSOC);
  110. }
  111. function fetchRow($stm)
  112. {
  113. return $stm->fetch(PDO::FETCH_ASSOC);
  114. }
  115. function insert($table, $data)
  116. {
  117. if (!$data) {
  118. return false;
  119. }
  120. $result = $this->parseQues($data);
  121. $sql = "INSERT INTO " . $table . " (" . implode(',', $result['fields']) . ") VALUES(" . implode(',', $result['ques']) . ")";
  122. $stm = $this->prepare($sql);
  123. $this->bindValue($stm, $result['values']);
  124. $this->execute($stm);
  125. return $this->db->lastInsertId();
  126. }
  127. function getTable($table)
  128. {
  129. $config = $this->getConfig();
  130. return $config['prefix'] . $table;
  131. }
  132. function delete($table, $where = [])
  133. {
  134. $result = $this->parseWhere($where);
  135. $where = $result && $result['where'] ? $result['where'] : '';
  136. $sql = "DELETE FROM " . $table . " " . $where;
  137. $stm = $this->prepare($sql);
  138. if ($result && $result['values']) {
  139. $this->bindValue($stm, $result['values']);
  140. }
  141. $this->execute($stm);
  142. return $stm->rowCount();
  143. }
  144. function deleteIn($table, $where = [])
  145. {
  146. $cons = '';
  147. if ($where) {
  148. foreach ($where as $key => $val) {
  149. $cons = 'WHERE ' . $key . ' IN (' . implode(',', $val) . ')';
  150. }
  151. }
  152. return $this->exec("DELETE FROM " . $table . " " . $cons);
  153. }
  154. function update($table, $set, $where = [])
  155. {
  156. $result = $this->parseWhere($where);
  157. $where = $result && $result['where'] ? $result['where'] : '';
  158. $data = $this->parseQues($set);
  159. //print_r( $data );
  160. $fields = '';
  161. foreach ($data['fields'] as $field) {
  162. $fields .= $fields ? ',' : '';
  163. $fields .= $field . '=?';
  164. }
  165. $sql = "UPDATE " . $table . " SET " . $fields . " " . $where;
  166. $stm = $this->prepare($sql);
  167. if ($result && $result['values']) {
  168. $arr = array_merge($data['values'], $result['values']);
  169. } else {
  170. $arr = $data['values'];
  171. }
  172. $this->bindValue($stm, $arr);
  173. $this->execute($stm);
  174. return $stm->rowCount();
  175. }
  176. function count($table, $where = array())
  177. {
  178. $result = $this->parseWhere($where);
  179. $where = $result && $result['where'] ? $result['where'] : '';
  180. $sql = "SELECT COUNT(*) AS num FROM " . $table . " " . $where;
  181. $stm = $this->prepare($sql);
  182. if ($result && $result['values']) {
  183. $this->bindValue($stm, $result['values']);
  184. }
  185. $this->execute($stm);
  186. $result = $this->fetchRow($stm);
  187. return $result['num'];
  188. }
  189. function sum($table, $fields = array(), $where = array())
  190. {
  191. $result = $this->parseWhere($where);
  192. $where = $result && $result['where'] ? $result['where'] : '';
  193. if (!$fields || !is_array($fields)) {
  194. return 0;
  195. }
  196. $sum = '';
  197. foreach ($fields as $key => $val) {
  198. $sum .= $sum ? ',' : '';
  199. $sum .= 'sum(' . $val . ') as ' . $key;
  200. }
  201. $sql = "SELECT " . $sum . " FROM " . $table . " " . $where;
  202. $stm = $this->prepare($sql);
  203. if ($result && $result['values']) {
  204. $this->bindValue($stm, $result['values']);
  205. }
  206. $this->execute($stm);
  207. $result = $this->fetchRow($stm);
  208. foreach ($result as $key => $val) {
  209. $result[$key] = $val == null ? 0 : number_format($val, 2, '.', '');
  210. }
  211. return $result;
  212. }
  213. function parseQues($data)
  214. {
  215. $result = [];
  216. foreach ($data as $key => $val) {
  217. $result['fields'][] = $key;
  218. $result['ques'][] = '?';
  219. $result['values'][] = $val;
  220. }
  221. return $result;
  222. }
  223. function parseWhere($where)
  224. {
  225. if (!$where) {
  226. return false;
  227. }
  228. if (!$where['fields']) {
  229. return false;
  230. }
  231. return array('where' => 'where ' . $where['fields'], 'values' => $where['values']);
  232. }
  233. function hasOper($key, $val)
  234. {
  235. if (strpos($val, '>') !== false || strpos($val, '>=') !== false || strpos($val, '<') !== false || strpos($val, '<=') !== false || strpos($val, '<>') !== false) {
  236. preg_match('/<>|>=|<=|>|<|/', $val, $match);
  237. return $key . $match[0] . '?';
  238. } else {
  239. return "{$key}=?";
  240. }
  241. }
  242. }