PHP PDO 使用类

心已赠人 2022-04-01 17:22 333阅读 0赞

PHP PDO 使用类

  1. <?php
  2. class MYPDO
  3. {
  4. protected static $_instance = null;
  5. protected $dbName = '';
  6. protected $dsn;
  7. protected $dbh;
  8. /**
  9. * 构造
  10. *
  11. * @return MyPDO
  12. */
  13. private function __construct()
  14. {
  15. try {
  16. $this->dsn = 'mysql:host=127.0.0.1;dbname=数据库名称;port=3306';
  17. $this->dbh = new PDO($this->dsn,'账号','密码');
  18. $this->dbh->exec('SET character_set_connection=utf8, character_set_results=utf8, character_set_client=binary');
  19. } catch (PDOException $e) {
  20. $this->outputError($e->getMessage());
  21. }
  22. }
  23. /**
  24. * 防止克隆
  25. *
  26. */
  27. private function __clone() {}
  28. /**
  29. * Singleton instance
  30. *
  31. * @return Object
  32. */
  33. public static function getInstance()
  34. {
  35. if (self::$_instance === null) {
  36. self::$_instance = new self();
  37. }
  38. return self::$_instance;
  39. }
  40. /**
  41. * Query 查询
  42. *
  43. * @param String $strSql SQL语句
  44. * @param String $queryMode 查询方式(All or Row)
  45. * @param Boolean $debug
  46. * @return Array
  47. */
  48. public function query($strSql, $queryMode = 'All', $debug = false)
  49. {
  50. if ($debug === true) $this->debug($strSql);
  51. $recordset = $this->dbh->query($strSql);
  52. $this->getPDOError();
  53. if ($recordset) {
  54. $recordset->setFetchMode(PDO::FETCH_ASSOC);
  55. if ($queryMode == 'All') {
  56. $result = $recordset->fetchAll();
  57. } elseif ($queryMode == 'Row') {
  58. $result = $recordset->fetch();
  59. }
  60. } else {
  61. $result = null;
  62. }
  63. return $result;
  64. }
  65. /**
  66. * select 查询所有记录
  67. * @param string $sql sql语句
  68. * @param Arrayt $where 查询条件
  69. * @return $res;
  70. **/
  71. public function select($sql,$where=''){
  72. $stmt=$this->dbh->prepare($sql);
  73. if($where){
  74. $stmt->execute($where);
  75. }else{
  76. $stmt->execute();
  77. }
  78. $res=$stmt->fetchAll(PDO::FETCH_ASSOC);//查询所有
  79. return $res;
  80. }
  81. /**
  82. * find 查询单条记录
  83. * @param string $sql sql语句
  84. * @param Array $where 查询条件
  85. * @return $res;
  86. **/
  87. public function find($sql,$where=''){
  88. $stmt=$this->dbh->prepare($sql);
  89. if($where){
  90. $stmt->execute($where);
  91. }else{
  92. $stmt->execute();
  93. }
  94. $res=$stmt->fetch(PDO::FETCH_ASSOC);//查询单个
  95. return $res;
  96. }
  97. /**
  98. * del 执行删除操作
  99. * @param string $sql sql语句
  100. * @param Array $where 查询条件
  101. * @return $res;
  102. **/
  103. public function del($sql,$where=''){
  104. $stmt=$this->dbh->prepare($sql);
  105. if($where){
  106. $stmt->execute($where);
  107. $res=$stmt->rowCount();
  108. }else{
  109. $res=false;
  110. }
  111. return $res;
  112. }
  113. /**
  114. * add 新增记录
  115. * @param string $sql sql语句
  116. * @param Array $data 新增内容
  117. * @return $res;
  118. **/
  119. public function add($table,$data=''){
  120. $this->checkFields($table, $data);
  121. $sql = "INSERT INTO `$table` (".implode(',', array_keys($data)).") VALUES (:".implode(',:',array_keys($data)).")";
  122. $stmt=$this->dbh->prepare($sql);//预处理语句
  123. $ret=$stmt->execute($data);//新增的数据
  124. $id=$this->dbh->lastInsertId();//新增的id
  125. if($ret){
  126. $res=$id;
  127. }else{
  128. $res=false;
  129. }
  130. return $res;
  131. }
  132. /**
  133. * save 修改记录
  134. * @param string $sql sql语句
  135. * @param Array $data
  136. * @return $res;
  137. **/
  138. public function save($table,$data='',$where=''){
  139. $this->checkFields($table, $data);
  140. if ($where) {
  141. $strSql = '';
  142. foreach ($data as $key => $value) {
  143. $strSql .= ",$key=:$key";
  144. }
  145. $strSql = substr($strSql,1);
  146. $strSql = "UPDATE `$table` SET $strSql WHERE $where";
  147. } else {
  148. $strSql = '';
  149. foreach ($data as $key => $value) {
  150. $strSql .= ",$key=:$key";
  151. }
  152. $strSql = substr($strSql,1);
  153. $strSql = "UPDATE `$table` SET $strSql ";
  154. }
  155. // if ($debug === true) $this->debug($strSql);
  156. $stmt=$this->dbh->prepare($strSql);//预处理语句
  157. $stmt->execute($data);//修改的数据
  158. $ret=$stmt->rowCount();//获取影响行数
  159. if($ret>0){
  160. $res=true;
  161. }else{
  162. $res=false;
  163. }
  164. return $res;
  165. }
  166. /**
  167. * Update 更新
  168. *
  169. * @param String $table 表名
  170. * @param Array $arrayDataValue 字段与值
  171. * @param String $where 条件
  172. * @param Boolean $debug
  173. * @return Int
  174. */
  175. public function update($table, $arrayDataValue, $where = '', $debug = false)
  176. {
  177. $this->checkFields($table, $arrayDataValue);
  178. if ($where) {
  179. $strSql = '';
  180. foreach ($arrayDataValue as $key => $value) {
  181. $strSql .= ", `$key`='$value'";
  182. }
  183. $strSql = substr($strSql, 1);
  184. $strSql = "UPDATE `$table` SET $strSql WHERE $where";
  185. } else {
  186. $strSql = "REPLACE INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
  187. }
  188. if ($debug === true) $this->debug($strSql);
  189. $result = $this->dbh->exec($strSql);
  190. $this->getPDOError();
  191. return $result;
  192. }
  193. /**
  194. * Insert 插入
  195. *
  196. * @param String $table 表名
  197. * @param Array $arrayDataValue 字段与值
  198. * @param Boolean $debug
  199. * @return Int
  200. */
  201. public function insert($table, $arrayDataValue, $debug = false)
  202. {
  203. $this->checkFields($table, $arrayDataValue);
  204. $strSql = "INSERT INTO `$table` (`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
  205. if ($debug === true) $this->debug($strSql);
  206. $result = $this->dbh->exec($strSql);
  207. $this->getPDOError();
  208. return $result;
  209. }
  210. /**
  211. * Replace 覆盖方式插入
  212. *
  213. * @param String $table 表名
  214. * @param Array $arrayDataValue 字段与值
  215. * @param Boolean $debug
  216. * @return Int
  217. */
  218. public function replace($table, $arrayDataValue, $debug = false)
  219. {
  220. $this->checkFields($table, $arrayDataValue);
  221. $strSql = "REPLACE INTO `$table`(`".implode('`,`', array_keys($arrayDataValue))."`) VALUES ('".implode("','", $arrayDataValue)."')";
  222. if ($debug === true) $this->debug($strSql);
  223. $result = $this->dbh->exec($strSql);
  224. $this->getPDOError();
  225. return $result;
  226. }
  227. /**
  228. * Delete 删除
  229. *
  230. * @param String $table 表名
  231. * @param String $where 条件
  232. * @param Boolean $debug
  233. * @return Int
  234. */
  235. public function delete($table, $where = '', $debug = false)
  236. {
  237. if ($where == '') {
  238. $this->outputError("'WHERE' is Null");
  239. } else {
  240. $strSql = "DELETE FROM `$table` WHERE $where";
  241. if ($debug === true) $this->debug($strSql);
  242. $result = $this->dbh->exec($strSql);
  243. $this->getPDOError();
  244. return $result;
  245. }
  246. }
  247. /**
  248. * execSql 执行SQL语句
  249. *
  250. * @param String $strSql
  251. * @param Boolean $debug
  252. * @return Int
  253. */
  254. public function execSql($strSql, $debug = false)
  255. {
  256. if ($debug === true) $this->debug($strSql);
  257. $result = $this->dbh->exec($strSql);
  258. $this->getPDOError();
  259. return $result;
  260. }
  261. /**
  262. * 获取字段最大值
  263. *
  264. * @param string $table 表名
  265. * @param string $field_name 字段名
  266. * @param string $where 条件
  267. */
  268. public function getMaxValue($table, $field_name, $where = '', $debug = false)
  269. {
  270. $strSql = "SELECT MAX(".$field_name.") AS MAX_VALUE FROM $table";
  271. if ($where != '') $strSql .= " WHERE $where";
  272. if ($debug === true) $this->debug($strSql);
  273. $arrTemp = $this->query($strSql, 'Row');
  274. $maxValue = $arrTemp["MAX_VALUE"];
  275. if ($maxValue == "" || $maxValue == null) {
  276. $maxValue = 0;
  277. }
  278. return $maxValue;
  279. }
  280. /**
  281. * 获取指定列的数量
  282. *
  283. * @param string $table
  284. * @param string $field_name
  285. * @param string $where
  286. * @param bool $debug
  287. * @return int
  288. */
  289. public function getCount($table, $field_name, $where = '', $debug = false)
  290. {
  291. $strSql = "SELECT COUNT($field_name) AS NUM FROM $table";
  292. if ($where != '') $strSql .= " WHERE $where";
  293. if ($debug === true) $this->debug($strSql);
  294. $arrTemp = $this->query($strSql, 'Row');
  295. return $arrTemp['NUM'];
  296. }
  297. /**
  298. * 获取表引擎
  299. *
  300. * @param String $dbName 库名
  301. * @param String $tableName 表名
  302. * @param Boolean $debug
  303. * @return String
  304. */
  305. public function getTableEngine($dbName, $tableName)
  306. {
  307. $strSql = "SHOW TABLE STATUS FROM $dbName WHERE Name='".$tableName."'";
  308. $arrayTableInfo = $this->query($strSql);
  309. $this->getPDOError();
  310. return $arrayTableInfo[0]['Engine'];
  311. }
  312. /**
  313. * beginTransaction 事务开始
  314. */
  315. public function beginTransaction()
  316. {
  317. $this->dbh->beginTransaction();
  318. }
  319. /**
  320. * commit 事务提交
  321. */
  322. public function commit()
  323. {
  324. $this->dbh->commit();
  325. }
  326. /**
  327. * rollback 事务回滚
  328. */
  329. public function rollback()
  330. {
  331. $this->dbh->rollback();
  332. }
  333. /**
  334. * transaction 通过事务处理多条SQL语句
  335. * 调用前需通过getTableEngine判断表引擎是否支持事务
  336. *
  337. * @param array $arraySql
  338. * @return Boolean
  339. */
  340. public function execTransaction($arraySql)
  341. {
  342. $retval = 1;
  343. $this->beginTransaction();
  344. foreach ($arraySql as $strSql) {
  345. if ($this->execSql($strSql) == 0) $retval = 0;
  346. }
  347. if ($retval == 0) {
  348. $this->rollback();
  349. return false;
  350. } else {
  351. $this->commit();
  352. return true;
  353. }
  354. }
  355. /**
  356. * checkFields 检查指定字段是否在指定数据表中存在
  357. *
  358. * @param String $table
  359. * @param array $arrayField
  360. */
  361. private function checkFields($table, $arrayFields)
  362. {
  363. $fields = $this->getFields($table);
  364. foreach ($arrayFields as $key => $value) {
  365. if (!in_array($key, $fields)) {
  366. $this->outputError("Unknown column `$key` in field list.");
  367. }
  368. }
  369. }
  370. /**
  371. * getFields 获取指定数据表中的全部字段名
  372. *
  373. * @param String $table 表名
  374. * @return array
  375. */
  376. private function getFields($table)
  377. {
  378. $fields = array();
  379. $recordset = $this->dbh->query("SHOW COLUMNS FROM $table");
  380. $this->getPDOError();
  381. $recordset->setFetchMode(PDO::FETCH_ASSOC);
  382. $result = $recordset->fetchAll();
  383. foreach ($result as $rows) {
  384. $fields[] = $rows['Field'];
  385. }
  386. return $fields;
  387. }
  388. /**
  389. * getPDOError 捕获PDO错误信息
  390. */
  391. private function getPDOError()
  392. {
  393. if ($this->dbh->errorCode() != '00000') {
  394. $arrayError = $this->dbh->errorInfo();
  395. $this->outputError($arrayError[2]);
  396. }
  397. }
  398. /**
  399. * debug
  400. *
  401. * @param mixed $debuginfo
  402. */
  403. private function debug($debuginfo)
  404. {
  405. var_dump($debuginfo);
  406. exit();
  407. }
  408. /**
  409. * 输出错误信息
  410. *
  411. * @param String $strErrMsg
  412. */
  413. private function outputError($strErrMsg)
  414. {
  415. throw new Exception('MySQL Error: '.$strErrMsg);
  416. }
  417. /**
  418. * destruct 关闭数据库连接
  419. */
  420. public function destruct()
  421. {
  422. $this->dbh = null;
  423. }
  424. }
  425. ?>

发表评论

表情:
评论列表 (有 0 条评论,333人围观)

还没有评论,来说两句吧...

相关阅读

    相关 PHP PDO

    PHP 数据对象 (PDO) 扩展为PHP访问数据库定义了一个轻量级的一致接口。 PDO 提供了一个数据访问抽象层,这意味着,不管使用哪种数据库,都可以用相同的函数(方法)来

    相关 PHP PDO

    PHP 数据对象 (PDO) 扩展为PHP访问数据库定义了一个轻量级的一致接口。 PDO 提供了一个数据访问抽象层,这意味着,不管使用哪种数据库,都可以用相同的函数(方法)来

    相关 PHP中的PDO详解

    PHP中的PDO(PHP Data Objects)类是一个强大的数据库访问抽象层,它提供了一种统一的接口来连接和操作不同类型的数据库。本文将详细介绍PDO类的使用以及相关的源