mysql.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. <?php
  2. defined('ONLY_ONLY_ONLY') or exit('Access Denied');
  3. define('SQL_THROW_EXCEPTION', 1);
  4. function mysqldb()
  5. {
  6. static $db;
  7. global $DB_CONFIG;
  8. if (empty($db)) {
  9. $DB_CONFIG['charset'] = empty($DB_CONFIG['charset']) ? 'utf8' : $DB_CONFIG['charset'];
  10. $db = new PdoUtil($DB_CONFIG);
  11. }
  12. return $db;
  13. }
  14. function pdo_query($sql, $params = array())
  15. {
  16. return mysqldb()->query($sql, $params);
  17. }
  18. function pdo_query2($sql, $params = array())
  19. {
  20. return mysqldb()->query2($sql, $params);
  21. }
  22. function pdo_query3($sql, $params = array())
  23. {
  24. return mysqldb()->query2_withtrans($sql, $params);
  25. }
  26. function pdo_fetch($sql, $params = array())
  27. {
  28. return mysqldb()->fetch($sql, $params);
  29. }
  30. function pdo_fetchcolumn($sql, $params = array(), $column = 0)
  31. {
  32. return mysqldb()->fetchcolumn($sql, $params, $column);
  33. }
  34. function pdo_fetchall($sql, $params = array(), $keyfield = '')
  35. {
  36. return mysqldb()->fetchall($sql, $params, $keyfield);
  37. }
  38. function pdo_update($table, $data = array(), $params = array(), $orwith = 'AND')
  39. {
  40. if ($params == 'empty') {
  41. $params = array();
  42. }
  43. return mysqldb()->update($table, $data, $params, $orwith);
  44. }
  45. function pdo_delete($table, $params = array(), $orwith = 'AND')
  46. {
  47. if ($params == 'empty') {
  48. $params = array();
  49. }
  50. return mysqldb()->delete($table, $params, $orwith);
  51. }
  52. function pdo_insert($table, $data = array(), $es = false)
  53. {
  54. return mysqldb()->insert($table, $data, $es);
  55. }
  56. function pdo_insertid()
  57. {
  58. return mysqldb()->insertid();
  59. }
  60. function pdo_fieldexists($tablename, $fieldname)
  61. {
  62. return mysqldb()->fieldexists($tablename, $fieldname);
  63. }
  64. function pdo_indexexists($tablename, $indexname)
  65. {
  66. return mysqldb()->indexexists($tablename, $indexname);
  67. }
  68. function pdo_fetchallfields($tablename)
  69. {
  70. $fields = pdo_fetchall("DESCRIBE {$tablename}", array(), 'Field');
  71. $fields = array_keys($fields);
  72. return $fields;
  73. }
  74. function pdo_buildSetSQL($suffix, $params)
  75. {
  76. return mysqldb()->splitForSQL($params, ',', $suffix);
  77. }
  78. function mysql_strvalue($str)
  79. {
  80. if (empty($str)) {
  81. $str = '';
  82. }
  83. $str = mb_ereg_replace("'", "", $str);
  84. $str = "'" . $str . "'";
  85. return $str;
  86. }
  87. function mysql_param(&$sqlParam, $fdname, $fdvalue)
  88. {
  89. if (empty($fdname)) {
  90. $fdname = 'sp';
  91. }
  92. $paraName = ":" . $fdname . "_" . count($sqlParam);
  93. $sqlParam[$paraName] = $fdvalue;
  94. return $paraName;
  95. }
  96. class PdoUtil
  97. {
  98. private $dbo;
  99. private $cfg;
  100. public function __construct($cfg)
  101. {
  102. if (empty($cfg)) {
  103. throw new Exception("PdoUtil发生异常,没有设置数据库配置信息!!");
  104. }
  105. $mysqlurl = "mysql:dbname={$cfg['database']};host={$cfg['host']};port={$cfg['port']};allowMultiQueries=true";
  106. try {
  107. $this->dbo = new PDO($mysqlurl, $cfg['username'], $cfg['password']);
  108. } catch (PDOException $e) {
  109. throw new Exception("PdoUtil发生异常,数据库连接失败,请检查数据库配置");
  110. }
  111. $sql = "SET NAMES '{$cfg['charset']}';";
  112. $this->dbo->exec($sql);
  113. $this->dbo->exec("SET sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';");
  114. $this->cfg = $cfg;
  115. if (SQL_THROW_EXCEPTION) {
  116. $this->errhandle($this->dbo->errorInfo(), $sql);
  117. }
  118. }
  119. public function table($table)
  120. {
  121. return $table;
  122. }
  123. public function errhandle($errors, $sql = "")
  124. {
  125. if (!empty($errors[0]) && !empty($errors[0]) && $errors[0] != '00000') {
  126. throw new Exception("数据库执行异常:" . $errors[2] . "\n sql语句:" . $sql . "\n" . @json_encode($errors));
  127. }
  128. return $errors;
  129. }
  130. public function query($sql, $params = array())
  131. {
  132. if (empty($params)) {
  133. $result = $this->dbo->exec($sql);
  134. if (SQL_THROW_EXCEPTION) {
  135. $this->errhandle($this->dbo->errorInfo(), $sql);
  136. }
  137. return $result;
  138. }
  139. $statement = $this->dbo->prepare($sql);
  140. $result = $statement->execute($params);
  141. if (SQL_THROW_EXCEPTION) {
  142. $this->errhandle($statement->errorInfo(), $sql);
  143. }
  144. if (!$result) {
  145. return false;
  146. } else {
  147. return $statement->rowCount();
  148. }
  149. }
  150. public function query2($sql, $params = array())
  151. {
  152. $statement = $this->dbo->prepare($sql);
  153. if ($statement) {
  154. $statement->closeCursor();
  155. }
  156. if (empty($params)) {
  157. $params = array();
  158. }
  159. $result = $statement->execute($params);
  160. if (SQL_THROW_EXCEPTION) {
  161. $this->errhandle($statement->errorInfo(), $sql);
  162. }
  163. $rowSet = array();
  164. do {
  165. try {
  166. if ($statement->columnCount() > 0) {
  167. $rs = $statement->fetchAll(pdo::FETCH_ASSOC);
  168. $rowSet[] = $rs;
  169. } else {
  170. $rowSet[] = $statement->rowCount();
  171. }
  172. } catch (PDOException $pdoex) {
  173. if ($statement) {
  174. $statement->closeCursor();
  175. }
  176. throw $pdoex;
  177. } catch (Throwable $ex) {
  178. if ($statement) {
  179. $statement->closeCursor();
  180. }
  181. throw $ex;
  182. }
  183. } while ($statement->nextRowset());
  184. $lastError = $statement->errorInfo();
  185. if ($statement) {
  186. $statement->closeCursor();
  187. }
  188. if (SQL_THROW_EXCEPTION) {
  189. $this->errhandle($lastError, $sql);
  190. }
  191. return $rowSet;
  192. }
  193. public function query2_withtrans($sql, $params = array())
  194. {
  195. $sql = trim($sql);
  196. if (mb_strlen($sql) > 0) {
  197. $last = mb_substr($sql, mb_strlen($sql) - 1);
  198. if (!($last === ";")) {
  199. $sql .= ";";
  200. }
  201. $sql = "SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;start transaction;" . $sql . "commit;";
  202. } else {
  203. throw new Exception("sql语句不能为空!");
  204. }
  205. $rowSet = $this->query2($sql, $params);
  206. if (count($rowSet) <= 3) {
  207. throw new Exception("怎么可能结果集小于等于3呢!");
  208. }
  209. $rowSetNew = array_slice($rowSet, 2, count($rowSet) - 3);
  210. return $rowSetNew;
  211. }
  212. public function fetchcolumn($sql, $params = array(), $column = 0)
  213. {
  214. $statement = $this->dbo->prepare($sql);
  215. $result = $statement->execute($params);
  216. if (SQL_THROW_EXCEPTION) {
  217. $this->errhandle($statement->errorInfo(), $sql);
  218. }
  219. if (!$result) {
  220. return false;
  221. } else {
  222. return $statement->fetchColumn($column);
  223. }
  224. }
  225. public function fetch($sql, $params = array())
  226. {
  227. $statement = $this->dbo->prepare($sql);
  228. $result = $statement->execute($params);
  229. if (SQL_THROW_EXCEPTION) {
  230. $this->errhandle($statement->errorInfo(), $sql);
  231. }
  232. if (!$result) {
  233. return false;
  234. } else {
  235. return $statement->fetch(pdo::FETCH_ASSOC);
  236. }
  237. }
  238. public function fetchall($sql, $params = array(), $keyfield = '')
  239. {
  240. $statement = $this->dbo->prepare($sql);
  241. $result = $statement->execute($params);
  242. if (SQL_THROW_EXCEPTION) {
  243. $this->errhandle($statement->errorInfo(), $sql);
  244. }
  245. if (!$result) {
  246. return false;
  247. } else {
  248. if (empty($keyfield)) {
  249. return $statement->fetchAll(pdo::FETCH_ASSOC);
  250. } else {
  251. $temp = $statement->fetchAll(pdo::FETCH_ASSOC);
  252. $rs = array();
  253. if (!empty($temp)) {
  254. foreach ($temp as $key => &$row) {
  255. if (isset($row[$keyfield])) {
  256. $rs[$row[$keyfield]] = $row;
  257. } else {
  258. $rs[] = $row;
  259. }
  260. }
  261. }
  262. return $rs;
  263. }
  264. }
  265. }
  266. public function update($table, $data = array(), $params = array(), $orwith = 'AND')
  267. {
  268. $fields = $this->splitForSQL($data, ',');
  269. $condition = $this->splitForSQL($params, $orwith);
  270. $params = array_merge($fields['params'], $condition['params']);
  271. $sql = "UPDATE " . $this->table($table) . " SET {$fields['fields']}";
  272. $sql .= $condition['fields'] ? ' WHERE ' . $condition['fields'] : '';
  273. return $this->query($sql, $params);
  274. }
  275. public function insert($table, $data = array(), $es = false)
  276. {
  277. $condition = $this->splitForSQL($data, ',');
  278. $backData = $this->query2("INSERT INTO " . $this->table($table) . " SET {$condition['fields']};select LAST_INSERT_ID() as lastInsertId;", $condition['params']);
  279. return intval($backData[1][0]["lastInsertId"]);
  280. }
  281. public function insertid()
  282. {
  283. return $this->dbo->lastInsertId();
  284. }
  285. public function delete($table, $params = array(), $orwith = 'AND')
  286. {
  287. $condition = $this->splitForSQL($params, $orwith);
  288. $sql = "DELETE FROM " . $this->table($table);
  289. $sql .= $condition['fields'] ? ' WHERE ' . $condition['fields'] : '';
  290. return $this->query($sql, $condition['params']);
  291. }
  292. public function splitForSQL($params, $orwith = ',', $suffix = '')
  293. {
  294. $result = array(
  295. 'fields' => ' 1 ', 'fieldnames' => ' 1 ', 'fieldvals' => ' 1 ',
  296. 'params' => array(),
  297. );
  298. $split = '';
  299. if (in_array(strtolower($orwith), array('and', 'or'))) {
  300. $suffix = '__';
  301. }
  302. if (!is_array($params)) {
  303. $result['fields'] = $params;
  304. return $result;
  305. }
  306. if (is_array($params)) {
  307. $result['fields'] = '';
  308. $result['fieldnames'] = '';
  309. $result['fieldvals'] = '';
  310. foreach ($params as $fields => $value) {
  311. $result['fieldnames'] .= $split . "`$fields`";
  312. $result['fieldvals'] .= $split . ":{$suffix}$fields";
  313. $result['fields'] .= $split . "`$fields` = :{$suffix}$fields";
  314. $split = ' ' . $orwith . ' ';
  315. $result['params'][":{$suffix}$fields"] = is_null($value) ? '' : $value;
  316. }
  317. }
  318. return $result;
  319. }
  320. public function fieldexists($tablename, $fieldname)
  321. {
  322. $isexists = $this->fetch("DESCRIBE " . $this->table($tablename) . " `{$fieldname}`");
  323. return !empty($isexists) ? true : false;
  324. }
  325. public function indexexists($tablename, $indexname)
  326. {
  327. if (!empty($indexname)) {
  328. $indexs = $this->fetchall("SHOW INDEX FROM " . $this->table($tablename));
  329. if (!empty($indexs) && is_array($indexs)) {
  330. foreach ($indexs as $row) {
  331. if ($row['Key_name'] == $indexname) {
  332. return true;
  333. }
  334. }
  335. }
  336. }
  337. return false;
  338. }
  339. }