心理咨询网
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <?php
  2. /**
  3. * @copyright (C)2016-2099 Hnaoyun Inc.
  4. * @author XingMeng
  5. * @email hnxsh@foxmail.com
  6. * @date 2017年8月30日
  7. * 数据库PDO驱动
  8. */
  9. namespace core\database;
  10. use core\basic\Config;
  11. class Pdo implements Builder
  12. {
  13. protected static $pdo;
  14. protected $master;
  15. protected $slave;
  16. protected $begin = false;
  17. private function __construct()
  18. {}
  19. public function __destruct()
  20. {
  21. if ($this->begin) { // 存在待提交的事务时自动进行提交
  22. $this->commit();
  23. }
  24. }
  25. // 获取单一实例,使用单一实例数据库连接类
  26. public static function getInstance()
  27. {
  28. if (! self::$pdo) {
  29. self::$pdo = new self();
  30. }
  31. return self::$pdo;
  32. }
  33. // 连接数据库,接受数据库连接参数,返回数据库连接对象
  34. public function conn($cfg)
  35. {
  36. if (get_db_type() == 'sqlite' && ! extension_loaded('pdo_sqlite')) {
  37. if (extension_loaded('SQLite3')) {
  38. error('未检测到您服务器环境的pdo_sqlite数据库扩展,请检查php.ini中是否已经开启该扩展!<br>另外,检测到您服务器支持sqlite3扩展,您也可以修改数据库配置连接驱动为sqlite试试!');
  39. } else {
  40. error('未检测到您服务器环境的pdo_sqlite数据库扩展,请检查php.ini中是否已经开启对应的数据库扩展!');
  41. }
  42. } elseif (get_db_type() == 'mysql' && ! extension_loaded('pdo_mysql')) {
  43. if (extension_loaded('mysqli')) {
  44. error('未检测到您服务器环境的pdo_mysqli数据库扩展,请检查php.ini中是否已经开启该扩展!<br>另外,检测到您服务器支持mysqli扩展,您也可以修改数据库配置连接驱动为mysqli试试!');
  45. } else {
  46. error('未检测到您服务器环境的pdo_mysqli数据库扩展,请检查php.ini中是否已经开启对应的数据库扩展!');
  47. }
  48. }
  49. $charset = Config::get('database.charset') ?: 'utf8';
  50. switch (Config::get('database.type')) {
  51. case 'pdo_mysql':
  52. $dsn = 'mysql:host=' . $cfg['host'] . ';port=' . $cfg['port'] . ';dbname=' . $cfg['dbname'] . ';charset=' . $charset;
  53. try {
  54. $conn = new \PDO($dsn, $cfg['user'], $cfg['passwd']);
  55. } catch (\PDOException $e) {
  56. error('PDO方式连接MySQL数据库错误:' . iconv('gbk', 'utf-8', $e->getMessage()));
  57. }
  58. break;
  59. case 'pdo_sqlite':
  60. $dsn = 'sqlite:' . ROOT_PATH . $cfg['dbname'];
  61. try {
  62. $conn = new \PDO($dsn);
  63. } catch (\PDOException $e) {
  64. error('PDO方式连接Sqlite数据库错误:' . iconv('gbk', 'utf-8', $e->getMessage()));
  65. }
  66. break;
  67. case 'pdo_pgsql':
  68. $dsn = 'pgsql:host=' . $cfg['host'] . ';port=' . $cfg['port'] . ';dbname=' . $cfg['dbname'];
  69. try {
  70. $conn = new \PDO($dsn, $cfg['user'], $cfg['passwd']);
  71. } catch (\PDOException $e) {
  72. error('PDO方式连接Pgsql数据库错误:' . iconv('gbk', 'utf-8', $e->getMessage()));
  73. }
  74. break;
  75. default:
  76. $dsn = Config::get('database.dsn');
  77. try {
  78. $conn = new \PDO($dsn, $cfg['user'], $cfg['passwd']);
  79. } catch (\PDOException $e) {
  80. error('PDO方式连接数据库错误:' . iconv('gbk', 'utf-8', $e->getMessage()));
  81. }
  82. break;
  83. }
  84. return $conn;
  85. }
  86. // 关闭自动提交,开启事务模式
  87. public function begin()
  88. {
  89. $this->master->beginTransaction();
  90. $this->begin = true;
  91. }
  92. // 提交事务
  93. public function commit()
  94. {
  95. $this->master->commit();
  96. $this->begin = false;
  97. }
  98. // 执行SQL语句,接受完整SQL语句,返回结果集对象
  99. public function query($sql, $type = 'master')
  100. {
  101. $time_s = microtime(true);
  102. switch ($type) {
  103. case 'master':
  104. if (! $this->master) {
  105. $cfg = Config::get('database');
  106. $this->master = $this->conn($cfg);
  107. if ($cfg['type'] == 'pdo_mysql') {
  108. $this->master->exec("SET sql_mode='NO_ENGINE_SUBSTITUTION'"); // MySql写入规避严格模式
  109. }
  110. }
  111. // sqlite时自动启动事务
  112. if ($cfg['type'] == 'pdo_sqlite' && ! $this->begin) {
  113. $this->begin();
  114. } elseif ($cfg['type'] == 'pdo_mysql' && Config::get('database.transaction') && ! $this->begin) { // 根据配置开启mysql事务,注意需要是InnoDB引擎
  115. $this->begin();
  116. }
  117. $result = $this->master->query($sql);
  118. if ($result === false) {
  119. $this->error($sql, 'master');
  120. }
  121. break;
  122. case 'slave':
  123. if (! $this->slave) {
  124. // 未设置从服务器时直接读取主数据库配置
  125. if (! $cfg = Config::get('database.slave')) {
  126. $cfg = Config::get('database');
  127. } else {
  128. // 随机选择从数据库
  129. if (is_multi_array($cfg)) {
  130. $count = count($cfg);
  131. $cfg = $cfg['slave' . mt_rand(1, $count)];
  132. }
  133. }
  134. $this->slave = $this->conn($cfg);
  135. }
  136. $result = $this->slave->query($sql) or $this->error($sql, 'slave');
  137. break;
  138. }
  139. return $result;
  140. }
  141. // 数据是否存在模型,接受完整SQL语句,返回boolean数据
  142. public function isExist($sql)
  143. {
  144. $result = $this->query($sql, 'slave');
  145. if ($result->fetch()) {
  146. return true;
  147. } else {
  148. return false;
  149. }
  150. }
  151. // 获取记录总量模型,接受数据库表名,返回int数据
  152. public function rows($table)
  153. {
  154. $sql = "SELECT count(*) FROM $table";
  155. $result = $this->query($sql, 'slave');
  156. if (! ! $row = $result->fetch(\PDO::FETCH_NUM)) {
  157. return $row[0];
  158. } else {
  159. return 0;
  160. }
  161. }
  162. // 读取字段数量模型,接受数据库表名,返回int数据
  163. public function fields($table)
  164. {
  165. $sql = "SELECT * FROM $table LIMIT 1";
  166. $result = $this->query($sql, 'slave');
  167. if ($result) {
  168. return $result->columnCount();
  169. } else {
  170. return false;
  171. }
  172. }
  173. /**
  174. * 获取表信息,接受数据库表名,返回表字段信息数组
  175. *
  176. * @param $table 表名
  177. */
  178. public function tableFields($table)
  179. {
  180. $rows = array();
  181. switch (Config::get('database.type')) {
  182. case 'pdo_mysql':
  183. $sql = "describe $table";
  184. $result = $this->query($sql, 'slave');
  185. while (! ! $row = $result->fetchObject()) {
  186. $rows[] = $row->Field;
  187. }
  188. break;
  189. case 'pdo_sqlite':
  190. $sql = "pragma table_info($table)";
  191. $result = $this->query($sql, 'slave');
  192. while (! ! $row = $result->fetchObject()) {
  193. $rows[] = $row->name;
  194. }
  195. break;
  196. case 'pdo_pgsql':
  197. $sql = "SELECT column_name FROM information_schema.columns WHERE table_name ='$table'";
  198. $result = $this->query($sql, 'slave');
  199. while (! ! $row = $result->fetchObject()) {
  200. $rows[] = $row->column_name;
  201. }
  202. break;
  203. default:
  204. return array();
  205. }
  206. return $rows;
  207. }
  208. /**
  209. * 查询一条数据模型,接受完整SQL语句,有数据返回对象数组,否则空数组
  210. * @$type 可以是MYSQLI_ASSOC(FETCH_ASSOC) ,MYSQLI_NUM(FETCH_NUM) ,MYSQLI_BOTH(FETCH_BOTH),不设置则返回对象模式
  211. */
  212. public function one($sql, $type = null)
  213. {
  214. $result = $this->query($sql, 'slave');
  215. $row = array();
  216. if ($type) {
  217. $type ++; // 与mysqli统一返回类型设置
  218. $row = $result->fetch($type);
  219. } else {
  220. $row = $result->fetchObject();
  221. }
  222. return $row;
  223. }
  224. /**
  225. * 查询多条数据模型,接受完整SQL语句,有数据返回二维对象数组,否则空数组
  226. * @$type 可以是MYSQLI_ASSOC(FETCH_ASSOC) ,MYSQLI_NUM(FETCH_NUM) ,MYSQLI_BOTH(FETCH_BOTH),不设置则返回对象模式
  227. */
  228. public function all($sql, $type = null)
  229. {
  230. $result = $this->query($sql, 'slave');
  231. $rows = array();
  232. if ($type) {
  233. $type ++; // 与mysqli统一返回类型设置
  234. $rows = $result->fetchAll($type);
  235. } else {
  236. while (! ! $row = $result->fetchObject()) {
  237. $rows[] = $row;
  238. }
  239. }
  240. return $rows;
  241. }
  242. // 数据增、删、改模型,接受完整SQL语句,返回影响的行数的int数据
  243. public function amd($sql)
  244. {
  245. $result = $this->query($sql, 'master');
  246. if ($result > 0) {
  247. return $result;
  248. } else {
  249. return 0;
  250. }
  251. }
  252. // 最近一次插入数据的自增字段值,返回int数据
  253. public function insertId()
  254. {
  255. return $this->master->lastInsertId();
  256. }
  257. // 执行多条SQL模型,成功返回true,否则false
  258. public function multi($sql)
  259. {
  260. $sqls = explode(';', $sql);
  261. foreach ($sqls as $key => $value) {
  262. $result = $this->query($value, 'master');
  263. }
  264. if ($result) {
  265. return true;
  266. } else {
  267. return false;
  268. }
  269. }
  270. // 显示执行错误
  271. protected function error($sql, $conn)
  272. {
  273. $errs = $this->$conn->errorInfo();
  274. $err = '错误:' . $errs[2];
  275. if (preg_match('/XPATH/i', $err)) {
  276. $err = '';
  277. }
  278. if ($this->begin) { // 如果是事务模式,发生错误,则回滚
  279. $this->$conn->rollBack();
  280. $this->begin = false;
  281. }
  282. // error('执行SQL发生错误!' . $err . '语句:' . $sql);
  283. error('执行SQL发生错误!' . $err);
  284. }
  285. //返回对象结果集
  286. public function fetchQuery($obj){
  287. return $obj->fetchAll();
  288. }
  289. }