下面來給各位同這介紹一個mysql PDO 操作類例子,希望些文章對大家會帶來幫助,文章是轉朋友的自己沒寫.
介紹:1、只有在執行select、update、delete、insert等操作時才會連接數據庫,2、采用PDO預處理方式,3、事務處理,4、錯誤輸出.
php代碼如下:
- <?php
- /**
- * mysql PDO 操作類
- * Created by PhpStorm.
- * User: sumiaowen
- * Date: 14-3-12
- * Time: 下午4:57
- * To change this template use File | Settings | File Templates.
- */
- class MyMysql
- {
- //pdo 鏈接 mysql dns
- static $dns = null;
- //mysql 用戶名
- static $username = null;
- //mysql 密碼
- static $password = null;
- //pdo 鏈接實例
- static $pdo = null;
- //調試
- public $debug = null;
- //開始事務
- private $_begin_transaction = false;
- /**
- * @param bool $debug 是否開啟調試,錯誤信息輸出
- * @param string $database 數據庫類別
- */
- public function __construct($debug = true, $database = 'default')
- {
- $this->debug = $debug;
- self::$dns = Yaf_Registry::get('config')->db->$database->dns;
- self::$username = Yaf_Registry::get('config')->db->$database->username;
- self::$password = Yaf_Registry::get('config')->db->$database->password;
- }
- /**
- * PDO對象實例化
- * @return null|PDO
- */
- static function instance()
- {
- if(is_null(self::$pdo))
- {
- try
- {
- self::$pdo = new PDO(self::$dns, self::$username, self::$password);
- self::$pdo->query('set names utf8');
- }
- catch(PDOException $e)
- {
- exit('PDOException: ' . $e->getMessage());
- }
- }
- return self::$pdo;
- }
- /**
- * 預處理執行 select sql語句
- * @param string $sql
- * @param array $parameters
- * @param int $option
- * @return array
- */
- public function query($sql, $parameters = array(), $option = PDO::FETCH_ASSOC)
- {
- self::$pdo || self::instance();
- $stmt = self::$pdo->prepare($sql);
- $stmt->execute($parameters);
- $tmp = array();
- while($row = $stmt->fetch($option))
- {
- $tmp[] = $row;
- }
- if($this->debug)
- {
- $this->error($stmt);
- }
- return $tmp;
- }
- /**
- * 預處理執行 update、delete、insert SQL語句
- * @param sting $sql
- * @param array $parameters
- * @return int 返回影響行數
- */
- public function execute($sql, $parameters = array())
- {
- self::$pdo || self::instance();
- $stmt = self::$pdo->prepare($sql);
- $stmt->execute($parameters);
- if($this->debug)
- {
- $this->error($stmt);
- }
- return $stmt->rowCount();
- }
- /**
- * 執行一條SQL語句
- * @param string $sql
- * @return int 返回影響行數
- */
- public function exec($sql)
- {
- self::$pdo || self::instance();
- $rows = self::$pdo->exec($sql);
- if($this->debug)
- {
- $this->error();
- }
- return $rows;
- }
- /**
- * 添加一條記錄
- * @param string $tableName 數據庫表名
- * @param array $data 需要添加的數據,一個 key|value 對應的數組,其中key為表字段名稱,value為插入的值,如:$data = array('keyword'=>'關鍵詞')
- * @return int 返回插入行的ID
- */
- public function insert($tableName, $data)
- {
- self::$pdo || self::instance();
- $fields = '`' . implode('`,`', array_keys($data)) . '`';
- $values = "'" . implode("','", $data) . "'";
- $sql = "INSERT INTO `{$tableName}`({$fields}) VALUES ({$values})";
- self::$pdo->exec($sql);
- if($this->debug)
- {
- $this->error();
- }
- return $this->getLastInsertId();
- }
- /**
- * 添加多條數據
- * @param string $tableName 數據庫表名
- * @param array $data 需要添加的數據,為一個二維數組,如:$data = array(array('fileld1'=>'value1','fileld2'=>'value2'),array('fileld1'=>'value1','fileld2'=>'value2'))
- * @return int 返回影響行數
- */
- public function insertBatch($tableName, $data)
- {
- self::$pdo || self::instance();
- $fields = '`' . implode('`,`', array_keys($data[0])) . '`';
- $tmp = array();
- foreach($data as $value)
- {
- $tmp[] = "'" . implode("','", $value) . "'";
- }
- $values = "(" . implode("),(", $tmp) . ")";
- $sql = "INSERT INTO `{$tableName}`({$fields}) VALUES {$values}";
- $rows = self::$pdo->exec($sql);
- if($this->debug)
- {
- $this->error();
- }
- return $rows;
- }
- /**
- * 根據主鍵更新數據
- * @param string $tableName 數據庫表名
- * @param array $where 更新條件,為 key|value 對應的數組,如:array('id'=>233)
- * @param array $data 更新數據,為 key|value 對應的數組,如:array('field1'=>'value1','field12'=>'value2')
- * @return int 成功返回影響行數,失敗返回錯誤信息
- */
- public function updateByPrimaryKey($tableName, $where, $data)
- {
- self::$pdo || self::instance();
- //條件
- $whereId = array_keys($where);
- $whereValue = array_values($where);
- $tmp = array();
- foreach($data as $key => $value)
- {
- $tmp[] = "`{$key}`='{$value}'";
- }
- $data = implode(',', $tmp);
- $sql = "UPDATE `{$tableName}` SET {$data} WHERE `{$whereId[0]}`='{$whereValue[0]}'";
- $rows = self::$pdo->exec($sql);
- if($this->debug)
- {
- $this->error();
- }
- return $rows;
- }
- /**
- * 根據主鍵刪除數據
- * @param string $tableName 數據庫表名
- * @param array $where 刪除條件,為 key|value 對應的數組,如:array('id'=>233)
- * @return int 成功返回影響行數,失敗返回錯誤信息
- */
- public function deleteByPrimaryKey($tableName, $where)
- {
- self::$pdo || self::instance();
- //條件
- $whereId = array_keys($where);
- $whereValue = array_values($where);
- $sql = "DELETE FROM `{$tableName}` WHERE `{$whereId[0]}`='{$whereValue[0]}'";
- $rows = self::$pdo->exec($sql);
- if($this->debug)
- {
- $this->error();
- }
- return $rows;
- }
- /**
- * 返回最后插入行的ID或序列值
- * @return int
- */
- public function getLastInsertId()
- {
- self::$pdo || self::instance();
- return self::$pdo->lastInsertId();
- }
- /**
- * 設置錯誤信息
- */
- public function error($stmt = '')
- {
- $error = $stmt ? $stmt->errorInfo() : self::$pdo->errorInfo();
- $msg = "SQLSTATE:{$error[0]}";
- if($error[1])
- {
- $msg .= " - ERRORCODE:{$error[1]}";
- }
- if($error[2])
- {
- $msg .= " - ERROR:{$error[2]}";
- }
- if($error[1] || $error[2])
- {
- exit($msg);
- }
- }
- /**
- * 事務開始
- * @return bool
- */
- public function begin()
- {
- self::$pdo || self::instance();
- //已經有事務,退出事務
- $this->rollback();
- if(!self::$pdo->beginTransaction())
- {
- return false;
- }
- return $this->_begin_transaction = true;
- }
- /**
- * 事務提交
- * @return bool
- */
- public function commit()
- {
- if($this->_begin_transaction)
- {
- $this->_begin_transaction = false;
- self::$pdo->commit();
- }
- return true;
- }
- /**
- * 事務回滾
- * @return bool
- */
- public function rollback()
- {
- if($this->_begin_transaction)
- {
- $this->_begin_transaction = false;
- self::$pdo->rollback();
- }//開源代碼Vevb.com
- return false;
- }
- /**
- * 關閉鏈接
- */
- public function close()
- {
- self::$pdo = null;
- }
- }
- ?>
新聞熱點
疑難解答