Advertisement
Guest User

Untitled

a guest
Oct 11th, 2017
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.48 KB | None | 0 0
  1. <?php
  2. /**
  3. * 简单的使用 PDO 操作 MySQL 数据库类
  4. * 类为静态类,全部静态调用
  5. */
  6. class Mysql
  7. {
  8. private static $conn;
  9.  
  10. public static function getInstance () {
  11. if (!self::$conn) {
  12. $mysql = Conf::getMysql();
  13. $_host = $mysql['host'];
  14. $_port = $mysql['port'];
  15. $_user = $mysql['user'];
  16. $_pass = $mysql['pass'];
  17. $_char = $mysql['char'];
  18. $_db = $mysql['db'];
  19. $dsn = "mysql:host=$_host;dbname=$_db;charset=$_char";
  20.  
  21. try {
  22. self::$conn = new PDO($dsn, $_user, $_pass);
  23. } catch (PDOException $e) {
  24. throw new Exception(Constants::E_CONNECT_TO_DB . ': '. $e->getMessage());
  25. }
  26. }
  27.  
  28. return self::$conn;
  29. }
  30.  
  31. /**
  32. * 插入数据到数据库
  33. * @param string $tableName 数据库名
  34. * @param array $data 要插入的数据
  35. */
  36. public static function insert ($tableName, $data) {
  37. if (gettype($tableName) !== 'string' || gettype($data) !== 'array') {
  38. throw new Exception(Constants::E_CALL_FUNCTION_PARAM);
  39. }
  40.  
  41. $prepareData = self::prepare($data);
  42. $prepareFieldsStr = implode(', ', array_keys($prepareData));
  43. $fieldsStr = implode(', ', array_keys($data));
  44. $sql = "INSERT INTO `$tableName` ($fieldsStr) VALUES ($prepareFieldsStr)";
  45.  
  46. // 执行 SQL 语句
  47. $query = self::raw($sql, $prepareData);
  48. return $query->rowCount();
  49. }
  50.  
  51. /**
  52. * 查询多行数据
  53. * @param string $tableName 数据库名
  54. * @param array $columns 查询的列名数组
  55. * @param array|string $condition 查询条件,若为字符串则会被直接拼接进 SQL 语句中,支持键值数组
  56. * @param string $operator condition 连接的操作符:and|or
  57. * @param string $suffix SQL 查询后缀,例如 order, limit 等其他操作
  58. * @return array
  59. */
  60. public static function select ($tableName, $columns = ['*'], $conditions = '', $operator = 'and', $suffix = '') {
  61. if ( gettype($tableName) !== 'string'
  62. || (gettype($conditions)!== 'array' && gettype($conditions) !== 'string')
  63. || gettype($columns) !== 'array'
  64. || gettype($operator) !== 'string'
  65. || gettype($suffix) !== 'string') {
  66. throw new Exception(Constants::E_CALL_FUNCTION_PARAM);
  67. }
  68.  
  69. list($condition, $execValues) = array_values(self::conditionProcess($conditions, $operator));
  70.  
  71. $column = implode(', ', $columns);
  72. // 拼接 SQL 语句
  73. $sql = "SELECT $column FROM `$tableName`";
  74.  
  75. // 如果有条件则拼接 WHERE 关键则
  76. if ($condition) {
  77. $sql .= " WHERE $condition";
  78. }
  79.  
  80. // 拼接后缀
  81. $sql .= " $suffix";
  82.  
  83. // 执行 SQL 语句
  84. $query = self::raw($sql, $execValues);
  85. $allResult = $query->fetchAll(PDO::FETCH_OBJ);
  86. return $allResult === NULL ? [] : $allResult;
  87. }
  88.  
  89. /**
  90. * 查询单行数据
  91. * @param string $tableName 数据库名
  92. * @param array $columns 查询的列名数组
  93. * @param array|string $condition 查询条件,若为字符串则会被直接拼接进 SQL 语句中,支持键值数组
  94. * @param string $operator condition 连接的操作符:and|or
  95. * @param string $suffix SQL 查询后缀,例如 order, limit 等其他操作
  96. * @return object
  97. */
  98. public static function row ($tableName, $columns = ['*'], $conditions = '', $operator = 'and', $suffix = '') {
  99. $rows = self::select($tableName, $columns, $conditions, $operator, $suffix);
  100. return count($rows) === 0 ? NULL : $rows[0];
  101. }
  102.  
  103. /**
  104. * 更新数据库
  105. * @param string $tableName 数据库名
  106. * @param array $updates 更新的数据对象
  107. * @param array|string $condition 查询条件,若为字符串则会被直接拼接进 SQL 语句中,支持键值数组
  108. * @param string $operator condition 连接的操作符:and|or
  109. * @param string $suffix SQL 查询后缀,例如 order, limit 等其他操作
  110. * @return number 受影响的行数
  111. */
  112. public static function update ($tableName, $updates, $conditions = '', $operator = 'and', $suffix = '') {
  113. if ( gettype($tableName) !== 'string'
  114. || gettype($updates) !== 'array'
  115. || (gettype($conditions)!== 'array' && gettype($conditions) !== 'string')
  116. || gettype($operator) !== 'string'
  117. || gettype($suffix) !== 'string') {
  118. throw new Exception(Constants::E_CALL_FUNCTION_PARAM);
  119. }
  120.  
  121. // 处理要更新的数据
  122. list($processedUpdates, $execUpdateValues) = array_values(self::conditionProcess($updates, ','));
  123.  
  124. // 处理条件
  125. list($condition, $execValues) = array_values(self::conditionProcess($conditions, $operator));
  126.  
  127. // 拼接 SQL 语句
  128. $sql = "UPDATE `$tableName` SET $processedUpdates";
  129.  
  130. // 如果有条件则拼接 WHERE 关键则
  131. if ($condition) {
  132. $sql .= " WHERE $condition";
  133. }
  134.  
  135. // 拼接后缀
  136. $sql .= " $suffix";
  137.  
  138. // 执行 SQL 语句
  139. $query = self::raw($sql, array_merge($execUpdateValues, $execValues));
  140. return $query->rowCount();
  141. }
  142.  
  143. /**
  144. * 删除数据
  145. * @param string $tableName 数据库名
  146. * @param array|string $condition 查询条件,若为字符串则会被直接拼接进 SQL 语句中,支持键值数组
  147. * @param string $operator condition 连接的操作符:and|or
  148. * @param string $suffix SQL 查询后缀,例如 order, limit 等其他操作
  149. * @return number 受影响的行数
  150. */
  151. public static function delete ($tableName, $conditions, $operator = 'and', $suffix = '') {
  152. if ( gettype($tableName) !== 'string'
  153. || ($conditions && gettype($conditions)!== 'array' && gettype($conditions) !== 'string')
  154. || gettype($operator) !== 'string'
  155. || gettype($suffix) !== 'string') {
  156. throw new Exception(Constants::E_CALL_FUNCTION_PARAM);
  157. }
  158.  
  159. // 处理条件
  160. list($condition, $execValues) = array_values(self::conditionProcess($conditions, $operator));
  161.  
  162. // 拼接 SQL 语句
  163. $sql = "DELETE FROM `$tableName` WHERE $condition $suffix";
  164.  
  165. // 执行 SQL 语句
  166. $query = self::raw($sql, $execValues);
  167. return $query->rowCount();
  168. }
  169.  
  170. /**
  171. * 执行原生 SQL 语句
  172. * @param string $sql 要执行的 SQL 语句
  173. * @param array $data SQL 语句的参数值
  174. */
  175. public static function raw ($sql, $execValues = []) {
  176. $query = self::getInstance()->prepare($sql);
  177. $result = $query->execute($execValues);
  178.  
  179. if ($result) {
  180. return $query;
  181. } else {
  182. $error = $query->errorInfo();
  183. throw new Exception(Constants::E_EXEC_SQL_QUERY . ': ' . $error[2]);
  184. }
  185. }
  186.  
  187. /**
  188. * 按照指定的规则处理条件数组
  189. * @example ['a' => 1, 'b' => 2] 会被转换为 ['a = :a and b = :b', [':a' => 1, ':b' => 2]]
  190. * @param array|string $conditions 条件数组或字符串
  191. * @param string $operator condition 连接的操作符:and|or
  192. */
  193. private static function conditionProcess ($conditions, $operator = 'and') {
  194. $condition = '';
  195. $execValues = [];
  196. if (gettype($conditions) === 'array') {
  197. $cdt = [];
  198.  
  199. foreach ($conditions as $key => $value) {
  200. if (gettype($value) === 'number') {
  201. array_push($cdt, $value);
  202. } else {
  203. array_push($cdt, $key . ' = :' . $key);
  204. $execValues[$key] = $value;
  205. }
  206. }
  207.  
  208. $condition = implode(' ' . $operator . ' ', $cdt);
  209. } else {
  210. $condition = $conditions;
  211. }
  212.  
  213. return [
  214. $condition,
  215. self::prepare($execValues)
  216. ];
  217. }
  218.  
  219. /**
  220. * 转换数据为 PDO 支持的 prepare 过的数据
  221. * @example ['a' => 1] 会被转换为 [':a' => 1]
  222. * @param array $dataArray 要转换的数据
  223. */
  224. private static function prepare ($dataArray) {
  225. $prepareData = [];
  226.  
  227. foreach ($dataArray as $field => $value) {
  228. $prepareData[':' . $field] = $value;
  229. }
  230.  
  231. return $prepareData;
  232. }
  233. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement