php mysql数据库操作mysql和pdo的实现
php mysql数据库操作mysql和pdo的实现
最近在项目中用到了pdo,之前一直用的mysql类,查了查手册,发现功能大同小异,于是我用接口封装了一个pdo类,实现了与mysql 的相同实现。
<?php /** * Created by PhpStorm. * User: jiangbo * Date: 2016/1/24 * Time: 1:05 * 与mysql接口一致(模型层调用一致),利用interface */ interface i_DAO{ //获取与前DAO的接口 public static function getInstance($config = array()); //执行sql的方法 public function query($sql = ''); //获取全部数据 public function fetchAll($sql = ''); //获取一行数据 public function fetchRow($sql = ''); //获取一个数据 public function fetchOne($sql = ''); //转义sql,防止注入 public function escapeString($str = ''); }
2. [文件] MySqlDB.class.php
<?php /** * Created by PhpStorm. * User: jiangbo * Date: 2016/1/19 * Time: 17:27 * 单例化的mysql类:3私1公 */ class MySqlDB implements i_DAO { private $_host; private $_port; private $_user; private $_password; private $_charset; private $_dbname; private $_link; /** * MySqlDB constructor. * @param array $config */ private function __construct($config = array()) { $this->_initServer($config);//初始化服务器信息 $this->_connectServer();//链接服务器 $this->_setCharset();//设置字符集编码 $this->_selectDB();//选择默认数据库 } private function __clone() { echo "不能克隆该对象", "<br>"; die(); } private static $_instance; public static function getInstance($config = array()) { if (!(static::$_instance instanceof static)) { static::$_instance = new static($config); } return static::$_instance; } private function _initServer($config) { $this->_host = isset($config['host']) ? $config['host'] : 'localhost'; $this->_port = isset($config['port']) ? $config['port'] : '3306'; $this->_user = isset($config['user']) ? $config['user'] : ''; $this->_password = $config['password']; $this->_charset = isset($config['charset']) ? $config['charset'] : 'UTF8'; $this->_dbname = isset($config['dbname']) ? $config['dbname'] : 'test'; } private function _connectServer() { $connect_result = @mysql_connect("$this->_host:$this->_port", $this->_user, $this->_password); if ($connect_result) { $this->_link = $connect_result; } else { echo '数据库连接失败,请确认服务器信息'; die(); } } private function _setCharset() { $sql = "SET NAMES $this->_charset"; $this->query($sql); } private function _selectDB() { $sql = "USE `$this->_dbname`"; $this->query($sql); } /** * 执行SQL语句 * @param string $sql * @return mixed 执行结果。查询类的SQL(select, show, desc),成功返回结果集资源, 失败返回false。非查询类(insert, delete, update),成功返回true,失败返回false. */ public function query($sql) { $query_result = @mysql_query($sql, $this->_link); if (false == $query_result) { echo "SQL执行失败:", "<br>"; echo "错误的SQL:", "<br>", $sql, "<br>"; echo "错误的消息为:", "<br>", mysql_errno($this->_link), "<br>"; die(); } else { return $query_result; } } /** * @param string $sql 通常为:select * from ... * @return array */ public function fetchRow($sql) { $result = $this->query($sql); $row = @mysql_fetch_assoc($result); @mysql_free_result($result); return $row; } /** * @param string $sql 通常为:select count(*) from ... * @return string 如果没有值就返回NULL */ public function fetchOne($sql) { $result = $this->query($sql); $row = @mysql_fetch_row($result); @mysql_free_result($result); if ($row) return $row[0]; else return NULL; } /** * @param string $sql 通常为:select * from ... where ..like 'han%' * @return array */ public function fetchAll($sql) { $result = $this->query($sql); $rows = array(); while ($row = @mysql_fetch_assoc($result)) $rows[] = $row; @mysql_free_result($result); return $rows; } /* * 关闭当前数据库连接, 一般无需使用. 连接会随php脚本结束自动关闭 */ /*public function close() { return @mysql_close($this->_link); }*/ /** * 防止sql注入:转义字符串,在模型中使用 * @param string $str 带转义的字符串 * @return string 带引号包裹的转义后的字符串 */ public function escapeString($str = '') { return "'" . mysql_real_escape_string($str, $this->_link) . "'"; } }
3. [文件] PDODB.class.php
<?php /** * Created by PhpStorm. * User: jiangbo * Date: 2016/1/24 * Time: 1:00 * dao层使用dao扩展封装实现 */ class PDODB implements i_DAO { private $_host; private $_port; private $_user; private $_password; private $_charset; private $_dbname; private $_dsn; private $_option; private $_pdo; /** * PDODB constructor. * @param array $config */ private function __construct($config = array()) { $this->_initServer($config); $this->_newPDO(); } private function _initServer($config) { $this->_host = isset($config['host']) ? $config['host'] : 'localhost'; $this->_port = isset($config['port']) ? $config['port'] : '3306'; $this->_user = isset($config['user']) ? $config['user'] : ''; $this->_password = $config['password']; $this->_charset = isset($config['charset']) ? $config['charset'] : 'UTF8'; $this->_dbname = isset($config['dbname']) ? $config['dbname'] : 'test'; } private function _newPDO() { //设置参数 $this->_setDSN();//设置数据源参数 $this->_setOption();//设置选项 $this->_getPDO();//得到PDO对象 } private function _setDSN() { $this->_dsn = "mysql:host=$this->_host;port=$this->_port;dbname=$this->_dbname"; } private function _setOption() { $this->_option = array( PDO::MYSQL_ATTR_INIT_COMMAND => "set names $this->_charset" ); } private function _getPDO() { $this->_pdo = new PDO($this->_dsn, $this->_user, $this->_password, $this->_option); } private function __clone() { echo "不能克隆该对象", "<br>"; die(); } private static $_instance; public static function getInstance($config = array()) { if (!(static::$_instance instanceof static)) { static::$_instance = new static($config); } return static::$_instance; } //执行方法,适用的场景 private static $_queryStr = array( "select", "show", "desc" ); public function query($sql = '') { //使用正则过滤,分别使用query和exec foreach (static::$_queryStr as $str){ if (preg_match("/^\s*".$str.".*?/i",$sql)){ //查询类 返回结果集对象 $result = $this->_pdo->query($sql); }else{ //非查询类 返回bool $result = $this->_pdo->exec($sql) !== false;//有可能是0 } //如果执行失败,报错 if($result === false){ $error_info = $this->errorInfo(); echo "SQL执行失败:", "<br>"; echo "错误的SQL:", "<br>", $sql, "<br>"; echo "错误的消息为:", "<br>", $error_info[2], "<br>"; die(); }else{ return $result; } break; } } public function fetchAll($sql = '') { $result = $this->query($sql); $rows = $result->fetchAll(PDO::FETCH_ASSOC); $result->closeCursor(); return $rows; } public function fetchRow($sql = '') { $result = $this->query($sql); $row = $result->fetch(PDO::FETCH_ASSOC); $result->closeCursor(); return $row; } public function fetchOne($sql = '') { $result = $this->query($sql); $string = $result->fetchColumn(); $result->closeCursor(); return $string; } public function escapeString($str = '') { return $this->_pdo->quote($str); } }
4. [代码]model中调用
<?php /** * Created by PhpStorm. * User: jiangbo * Date: 2016/1/19 * Time: 1:02 * 基础模型类 */ class Model{ /** * DAO : data access object */ protected $_dao;//存储实例化好的数据库对象 /** * Model constructor. */ public function __construct() { $this->_initDAO();//初始化基础模型 } protected function _initDAO(){ $config = array( 'host' => '***', 'user' => '***', 'password' => '', 'dbname' => '***' ); //$this->_dao = MySqlDB::getInstance($config);//调用mysqldb $this->_dao = PDODB::getInstance($config);//调用pdo } }
以上就是php mysql数据库操作mysql和pdo的实现的内容,更多相关内容请关注PHP中文网(www.php.cn)!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

PHP和Python各有優勢,選擇依據項目需求。 1.PHP適合web開發,尤其快速開發和維護網站。 2.Python適用於數據科學、機器學習和人工智能,語法簡潔,適合初學者。

PHP用於構建動態網站,其核心功能包括:1.生成動態內容,通過與數據庫對接實時生成網頁;2.處理用戶交互和表單提交,驗證輸入並響應操作;3.管理會話和用戶認證,提供個性化體驗;4.優化性能和遵循最佳實踐,提升網站效率和安全性。

PHP在電子商務、內容管理系統和API開發中廣泛應用。 1)電子商務:用於購物車功能和支付處理。 2)內容管理系統:用於動態內容生成和用戶管理。 3)API開發:用於RESTfulAPI開發和API安全性。通過性能優化和最佳實踐,PHP應用的效率和可維護性得以提升。

PHP仍然具有活力,其在現代編程領域中依然佔據重要地位。 1)PHP的簡單易學和強大社區支持使其在Web開發中廣泛應用;2)其靈活性和穩定性使其在處理Web表單、數據庫操作和文件處理等方面表現出色;3)PHP不斷進化和優化,適用於初學者和經驗豐富的開發者。

PHP主要是過程式編程,但也支持面向對象編程(OOP);Python支持多種範式,包括OOP、函數式和過程式編程。 PHP適合web開發,Python適用於多種應用,如數據分析和機器學習。

PHP和Python各有優劣,選擇取決於項目需求和個人偏好。 1.PHP適合快速開發和維護大型Web應用。 2.Python在數據科學和機器學習領域佔據主導地位。

PHP的核心優勢包括易於學習、強大的web開發支持、豐富的庫和框架、高性能和可擴展性、跨平台兼容性以及成本效益高。 1)易於學習和使用,適合初學者;2)與web服務器集成好,支持多種數據庫;3)擁有如Laravel等強大框架;4)通過優化可實現高性能;5)支持多種操作系統;6)開源,降低開發成本。

PHP在數據庫操作和服務器端邏輯處理中使用MySQLi和PDO擴展進行數據庫交互,並通過會話管理等功能處理服務器端邏輯。 1)使用MySQLi或PDO連接數據庫,執行SQL查詢。 2)通過會話管理等功能處理HTTP請求和用戶狀態。 3)使用事務確保數據庫操作的原子性。 4)防止SQL注入,使用異常處理和關閉連接來調試。 5)通過索引和緩存優化性能,編寫可讀性高的代碼並進行錯誤處理。
