<?php//单例模式封装MyPDO类classMyPDO{privatestatic$instance;private$host;//主机private$port;//端口号private$dbname;//数据库名private$charset;//字符编码集private$user;//数据库用户名private$pwd;//数据库密码private$dns;private$dbtype;//数据库的类型private$pdo;//pdo对象//私有构造器privatefunction__construct($parma){$this->initParma($parma);$this->initPDO();$this->initException();}//私有克隆方法privatefunction__clone(){}publicstaticfunctiongetInstance($parma){if(!self::$instanceinstanceofself)self::$instance=newself($parma);returnself::$instance;}//初始化参数privatefunctioninitParma($parma){$this->host=$parma['host']??'127.0.0.1';$this->port=$parma['port']??'3306';$this->dbname=$parma['dbname']??'';$this->charset=$parma['charset']??'utf8';$this->user=$parma['user']??'root';$this->pwd=$parma['pwd']??'root';$this->dbtype=$parma['type']??'mysql';}//初始化PDOprivatefunctioninitPDO(){try{$this->dns="{$this->dbtype}:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}";$this->pdo=newPDO($this->dns,$this->user,$this->pwd);}catch(PDOException$ex){$this->showException($ex);exit();}}//执行sqlpublicfunctionexec($sql){try{return$this->pdo->exec($sql);}catch(PDOException$ex){$this->showException($ex,$sql);exit();}}//最后一次插入的id号publicfunctionlastinsertnum(){return$this->pdo->lastInsertId();}//获取所有数据,返回二维数组publicfunctionfetchAll($sql,$type=''){try{$stmt=$this->pdo->query($sql);$type=$this->getType($type);return$stmt->fetchAll($type);}catch(PDOException$ex){$this->showException($ex,$sql);}}//获取一维数组publicfunctionfetchRow($sql,$type=''){try{$stmt=$this->pdo->query($sql);$type=$this->getType($type);return$stmt->fetch($type);}catch(PDOException$ex){$this->showException($ex,$sql);}}//获取一行一列publicfunctionfetchColumn($sql){try{$stmt=$this->pdo->query($sql);return$stmt->fetchColumn();}catch(PDOException$ex){$this->showException($ex,$sql);}}//判断匹配的类型privatefunctiongetType($type){switch($type){case'num':returnPDO::FETCH_NUM;case'both':returnPDO::FETCH_BOTH;case'obj':returnPDO::FETCH_OBJ;default:returnPDO::FETCH_ASSOC;}}//设置异常模式privatefunctioninitException(){$this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);}//异常显示privatefunctionshowException($ex,$sql=''){if($sql!=''){echo'SQL语句执行失败<br>';echo'错误的SQL语句为'.$sql.'<br>';}echo'错误编号为:'.$ex->getCode().'<br>';echo'错误行号为:'.$ex->getLine().'<br>';echo'错误信息为:'.$ex->getMessage().'<br>';echo'错误文件为:'.$ex->getFile().'<br>';}}//测试$parma=array('dbname'=>'data');$mypdo=MyPDO::getInstance($parma);//$mypdo->exec("insert into user values (null,'kk','2015482635')");//echo $mypdo->lastinsertnum();$list=$mypdo->fetchColumn('select name from user where id=4');echo'<pre>';print_r($list);