看到你,梁松远的博客

位置 » 主页 » 代码分享 » pdomysql.php pdo形式操作mysql数据库类

pdomysql.php pdo形式操作mysql数据库类

 class lib_db_pdomysql
 {
 public function __construct($config){
 $config['dsn'] = 'mysql:host=' . $config['host'] . ';dbname=' . $config['dbname'];
 $this->config = $config;
 
 $this->connect();
 }
 
 public function connect(){
 $this->pdo = new PDO($this->config['dsn'], $this->config['username'], $this->config['password']);
 $this->pdo->query('set names utf8;');
 $this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
 }
 
 /*数据库关闭*/
 public function close(){
 $this->pdo = null;
 }
 
 public function query($sql = null){
 if(!$sql){
 $sql = $this->select->__toString();
 }
 $res = $this->pdo->query($sql);
 if($res){
 $this->res = $res;
 }
 return $res;
 }
 
 public function select(){
 return $this->select = new lib_db_select();
 }
 
 public function exec($sql = null){
 if(!$sql){
 $sql = $this->select->__toString();
 }
 $res = $this->pdo->exec($sql);
 if($res){
 $this->res = $res;
 }
 }
 
 public function lastInsertId(){
 return $this->pdo->lastInsertId();
 }
 
 public function fetchAll($sql = null){
 $this->query($sql);
 $result = $this->res->fetchAll();
 return $result;
 }
 public function fetchRow($sql = null){
 $this->query($sql);
 
 $result = $this->res->fetch();
 return $result;
 }
 public function fetchOne($sql = null){
 $this->query($sql);
 $result = $this->res->fetch();
 return $result;
 }
 
 public function insert($table,$data){
 $table = "`" . $table . "`";
 $string = array();
 foreach($data as $key=>$val){
 $string[] = "`" . $key . "` = '" . addslashes($val) . "'";
 }
 $string = "INSERT INTO $table SET " . implode(', ', $string);
 $this->exec($string);
 $return = $this->lastInsertId();
 return $return;
 }
 
 public function update($table,$data,$where){
 $table = "`" . $table . "`";
 $string = array();
 foreach($data as $key=>$val){
 $string[] = "`" . $key . "` = '" . addslashes($val) . "'";
 }
 $string = "UPDATE $table SET " . implode(', ', $string) . ' WHERE ' . $where;
 $this->exec($string);
 $return = $this->res;
 return $return;
 }
 
 public function delete($table,$where){
 $table = "`" . $table . "`";
 $string = 'DELETE FROM ' . $table . ' WHERE ' . $where;
 $this->exec($string);
 $return = $this->res;
 return $return;
 }
 
 public function fetch(){
 $result = $this->res->fetch();
 
 return $result;
 }
 
 public function getServerVersion()
 {
 $this->query('select VERSION() as n');
 $version = $this->fetch();
 $version = substr(preg_replace('/[^\d]*/i','',$version['n']),0,4);
 $major = (int) ($version / 1000);
 $minor = (int) ($version % 1000 / 100);
 $revision = (int) ($version % 100);
 $version = $major . '.' . $minor . '.' . $revision;
 return $version;
 }
 }