db.class.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. <?php
  2. /**
  3. * 数据库操作类
  4. *
  5. * [WeEngine System] Copyright (c) 2013 WE7.CC
  6. */
  7. //defined('IN_IA') or exit('Access Denied');
  8. define('PDO_DEBUG', true);
  9. class DB {
  10. private $pdo;
  11. private $cfg;
  12. private $errors = array();
  13. public function getPDO() {
  14. return $this->pdo;
  15. }
  16. public function __construct($name = 'default') {
  17. global $config;
  18. $cfg = $config;
  19. if(empty($cfg)) {
  20. die("没有找到名为 {$config['db']['database']} 的数据库配置项.");
  21. }
  22. $dsn = "mysql:dbname={$config['db']['database']};host={$config['db']['host']};port={$config['db']['port']}";
  23. $dbclass = '';
  24. $options = array();
  25. if (class_exists('PDO')) {
  26. if (extension_loaded("pdo_mysql") && in_array('mysql', PDO::getAvailableDrivers())) {
  27. $dbclass = 'PDO';
  28. $options = array(PDO::ATTR_PERSISTENT =>$config['db']['pconnect']);
  29. } else {
  30. include 'PDO.class.php';
  31. $dbclass = '_PDO';
  32. }
  33. } else {
  34. include 'PDO.class.php';
  35. $dbclass = 'PDO';
  36. }
  37. $this->pdo = new $dbclass($dsn, $config['db']['username'], $config['db']['password'], $options);
  38. $sql = "SET NAMES '{$config['db']['charset']}';";
  39. $this->pdo->exec($sql);
  40. $this->pdo->exec("SET sql_mode='';");
  41. $this->cfg = $cfg;
  42. if(PDO_DEBUG) {
  43. $info = array();
  44. $info['sql'] = $sql;
  45. $info['error'] = $this->pdo->errorInfo();
  46. $this->debug(false, $info);
  47. }
  48. }
  49. public function query($sql, $params = array()) {
  50. if (empty($params)) {
  51. $result = $this->pdo->exec($sql);
  52. if(PDO_DEBUG) {
  53. $info = array();
  54. $info['sql'] = $sql;
  55. $info['error'] = $this->pdo->errorInfo();
  56. $this->debug(false, $info);
  57. }
  58. return $result;
  59. }
  60. $statement = $this->pdo->prepare($sql);
  61. if (!is_object($statement)) {
  62. $this->debug(false, array('sql' => $sql, 'error' => array('', '-1', '当前连接数据库用户没有执行该条语句的权限,请检查mysql权限配置')));
  63. return false;
  64. }
  65. $result = $statement->execute($params);
  66. if(PDO_DEBUG) {
  67. $info = array();
  68. $info['sql'] = $sql;
  69. $info['params'] = $params;
  70. $info['error'] = $statement->errorInfo();
  71. $this->debug(false, $info);
  72. }
  73. if (!$result) {
  74. return false;
  75. } else {
  76. return $statement->rowCount();
  77. }
  78. }
  79. public function fetchcolumn($sql, $params = array(), $column = 0) {
  80. $statement = $this->pdo->prepare($sql);
  81. if (!is_object($statement)) {
  82. $this->debug(false, array('sql' => $sql, 'error' => array('', '-1', '当前连接数据库用户没有执行该条语句的权限,请检查mysql权限配置')));
  83. return false;
  84. }
  85. $result = $statement->execute($params);
  86. if(PDO_DEBUG) {
  87. $info = array();
  88. $info['sql'] = $sql;
  89. $info['params'] = $params;
  90. $info['error'] = $statement->errorInfo();
  91. $this->debug(false, $info);
  92. }
  93. if (!$result) {
  94. return false;
  95. } else {
  96. return $statement->fetchColumn($column);
  97. }
  98. }
  99. public function fetch($sql, $params = array()) {
  100. $statement = $this->pdo->prepare($sql);
  101. if (!is_object($statement)) {
  102. $this->debug(false, array('sql' => $sql, 'error' => array('', '-1', '当前连接数据库用户没有执行该条语句的权限,请检查mysql权限配置')));
  103. return false;
  104. }
  105. $result = $statement->execute($params);
  106. if(PDO_DEBUG) {
  107. $info = array();
  108. $info['sql'] = $sql;
  109. $info['params'] = $params;
  110. $info['error'] = $statement->errorInfo();
  111. $this->debug(false, $info);
  112. }
  113. if (!$result) {
  114. return false;
  115. } else {
  116. return $statement->fetch(pdo::FETCH_ASSOC);
  117. }
  118. }
  119. public function fetchall($sql, $params = array(), $keyfield = '') {
  120. $statement = $this->pdo->prepare($sql);
  121. if (!is_object($statement)) {
  122. $this->debug(false, array('sql' => $sql, 'error' => array('', '-1', '当前连接数据库用户没有执行该条语句的权限,请检查mysql权限配置')));
  123. return false;
  124. }
  125. $result = $statement->execute($params);
  126. if(PDO_DEBUG) {
  127. $info = array();
  128. $info['sql'] = $sql;
  129. $info['params'] = $params;
  130. $info['error'] = $statement->errorInfo();
  131. $this->debug(false, $info);
  132. }
  133. if (!$result) {
  134. return false;
  135. } else {
  136. if (empty($keyfield)) {
  137. return $statement->fetchAll(pdo::FETCH_ASSOC);
  138. } else {
  139. $temp = $statement->fetchAll(pdo::FETCH_ASSOC);
  140. $rs = array();
  141. if (!empty($temp)) {
  142. foreach ($temp as $key => &$row) {
  143. if (isset($row[$keyfield])) {
  144. $rs[$row[$keyfield]] = $row;
  145. } else {
  146. $rs[] = $row;
  147. }
  148. }
  149. }
  150. return $rs;
  151. }
  152. }
  153. }
  154. public function update($table, $data = array(), $params = array(), $glue = 'AND') {
  155. $fields = $this->implode($data, ',');
  156. $condition = $this->implode($params, $glue);
  157. $params = array_merge($fields['params'], $condition['params']);
  158. $sql = "UPDATE " . $this->tablename($table) . " SET {$fields['fields']}";
  159. $sql .= $condition['fields'] ? ' WHERE '.$condition['fields'] : '';
  160. return $this->query($sql, $params);
  161. }
  162. public function insert($table, $data = array(), $replace = FALSE) {
  163. $cmd = $replace ? 'REPLACE INTO' : 'INSERT INTO';
  164. $condition = $this->implode($data, ',');
  165. return $this->query("$cmd " . $this->tablename($table) . " SET {$condition['fields']}", $condition['params']);
  166. }
  167. public function insertid() {
  168. return $this->pdo->lastInsertId();
  169. }
  170. public function delete($table, $params = array(), $glue = 'AND') {
  171. $condition = $this->implode($params, $glue);
  172. $sql = "DELETE FROM " . $this->tablename($table);
  173. $sql .= $condition['fields'] ? ' WHERE '.$condition['fields'] : '';
  174. return $this->query($sql, $condition['params']);
  175. }
  176. public function begin() {
  177. $this->pdo->beginTransaction();
  178. }
  179. public function commit() {
  180. $this->pdo->commit();
  181. }
  182. public function rollback() {
  183. $this->pdo->rollBack();
  184. }
  185. private function implode($params, $glue = ',') {
  186. $result = array('fields' => ' 1 ', 'params' => array());
  187. $split = '';
  188. $suffix = '';
  189. if (in_array(strtolower($glue), array('and', 'or'))) {
  190. $suffix = '__';
  191. }
  192. if (!is_array($params)) {
  193. $result['fields'] = $params;
  194. return $result;
  195. }
  196. if (is_array($params)) {
  197. $result['fields'] = '';
  198. foreach ($params as $fields => $value) {
  199. $result['fields'] .= $split . "`$fields` = :{$suffix}$fields";
  200. $split = ' ' . $glue . ' ';
  201. $result['params'][":{$suffix}$fields"] = is_null($value) ? '' : $value;
  202. }
  203. }
  204. return $result;
  205. }
  206. public function run($sql, $stuff = 'ims_') {
  207. if(!isset($sql) || empty($sql)) return;
  208. $sql = str_replace("\r", "\n", str_replace(' ' . $stuff, ' ' . $this->cfg['tablepre'], $sql));
  209. $sql = str_replace("\r", "\n", str_replace(' `' . $stuff, ' `' . $this->cfg['tablepre'], $sql));
  210. $ret = array();
  211. $num = 0;
  212. foreach(explode(";\n", trim($sql)) as $query) {
  213. $ret[$num] = '';
  214. $queries = explode("\n", trim($query));
  215. foreach($queries as $query) {
  216. $ret[$num] .= (isset($query[0]) && $query[0] == '#') || (isset($query[1]) && isset($query[1]) && $query[0].$query[1] == '--') ? '' : $query;
  217. }
  218. $num++;
  219. }
  220. unset($sql);
  221. foreach($ret as $query) {
  222. $query = trim($query);
  223. if($query) {
  224. $this->query($query);
  225. }
  226. }
  227. }
  228. public function fieldexists($tablename, $fieldname) {
  229. $isexists = $this->fetch("DESCRIBE " . $this->tablename($tablename) . " `{$fieldname}`");
  230. return !empty($isexists) ? true : false;
  231. }
  232. public function indexexists($tablename, $indexname) {
  233. if (!empty($indexname)) {
  234. $indexs = pdo_fetchall("SHOW INDEX FROM " . $this->tablename($tablename));
  235. if (!empty($indexs) && is_array($indexs)) {
  236. foreach ($indexs as $row) {
  237. if ($row['Key_name'] == $indexname) {
  238. return true;
  239. }
  240. }
  241. }
  242. }
  243. return false;
  244. }
  245. public function tablename($table) {
  246. return "`{$this->cfg['db']['tablepre']}{$table}`";
  247. }
  248. public function debug($output = true, $append = array()) {
  249. if(!empty($append)) {
  250. $output = false;
  251. array_push($this->errors, $append);
  252. }
  253. if($output) {
  254. print_r($this->errors);
  255. } else {
  256. if (!empty($append['error'][1])) {
  257. $traces = debug_backtrace();
  258. $ts = '';
  259. foreach($traces as $trace) {
  260. $trace['file'] = str_replace('\\', '/', $trace['file']);
  261. $trace['file'] = str_replace(IA_ROOT, '', $trace['file']);
  262. $ts .= "file: {$trace['file']}; line: {$trace['line']}; <br />";
  263. }
  264. $params = var_export($append['params'], true);
  265. die("SQL: <br/>{$append['sql']}<hr/>Params: <br/>{$params}<hr/>SQL Error: <br/>{$append['error'][2]}<hr/>Traces: <br/>{$ts}");
  266. }
  267. }
  268. return $this->errors;
  269. }
  270. }