- 本文可以结合我的文章设计模式中的-单例模式
再进行封装下
使用类时使用以下代码即可
$pdo = DBPDO::get_instance();
$pdo->test();
$user='root';
$pass='123456';
$dsn='mysql:host=localhost;dbname=test';
//$pdo = new PDO($dsn,$user,$pass);
//
try{
//创建pdo对象
$pdo=new PDO($dsn,$user,$pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE,2);//异常报错
$pdo->exec("set names utf8");
}catch(PDOException $e){
echo $e->getMessage();
}
//$sql="insert into dlxxx(payamount,username,remark,orderid,payip,paytype,returnurl,notifyurl,version,consdition)values(?,?,?,?,?,?,?,?,?,?)";
$sql = "insert into users(username,password,amount) values(?,?,?)";
$stmt = $pdo->prepare($sql);
$aa = '2';
$stmt->bindParam(1,$user);//不能直接给数据
$stmt->bindParam(2,$pass);
$stmt->bindParam(3,$aa);
$ss = $stmt->execute();
var_dump($ss);
注意
bindParam()
绑定的参数必须是一个变量 ,bindValue()
既可以绑定变量,又可以绑定具体值
PDO连接数据库的类
<?php
//定义数据库信息
header("Content-type:text/html; charset=utf-8");
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PWD', '123456');
define('DB_NAME', 'test');
class DBPDO {
private static $instance;
public $dsn;
public $dbuser;
public $dbpwd;
public $sth;
public $dbh;
//初始化
function __construct() {
$this->dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME;
$this->dbuser = DB_USER;
$this->dbpwd = DB_PWD;
$this->connect();
$this->dbh->query("SET NAMES 'UTF8'");
$this->dbh->query("SET TIME_ZONE = '+8:00'");
}
//连接数据库
public function connect() {
try {
$this->dbh = new PDO($this->dsn, $this->dbuser, $this->dbpwd);
}
catch(PDOException $e) {
exit('连接失败:'.$e->getMessage());
}
}
//获取表字段
public function getFields($table='vista_order') {
$this->sth = $this->dbh->query("DESCRIBE $table");
$this->getPDOError();
$this->sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $this->sth->fetchAll();
$this->sth = null;
return $result;
}
//插入数据
public function insert($sql) {
if($this->dbh->exec($sql)) {
$this->getPDOError();
return $this->dbh->lastInsertId();
}
return false;
}
//删除数据
public function delete($sql) {
if(($rows = $this->dbh->exec($sql)) > 0) {
$this->getPDOError();
return $rows;
}
else {
return false;
}
}
//更改数据
public function update($sql) {
if(($rows = $this->dbh->exec($sql)) > 0) {
$this->getPDOError();
return $rows;
}
return false;
}
//获取数据
public function select($sql) {
$this->sth = $this->dbh->query($sql);
$this->getPDOError();
$this->sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $this->sth->fetchAll();
$this->sth = null;
return $result;
}
//获取数目
public function count($sql) {
$count = $this->dbh->query($sql);
$this->getPDOError();
return $count->fetchColumn();
}
//获取PDO错误信息
private function getPDOError() {
if($this->dbh->errorCode() != '00000') {
$error = $this->dbh->errorInfo();
exit($error[2]);
}
}
//关闭连接
public function __destruct() {
$this->dbh = null;
}
}
//eg: an example for operate select
$test = new DBPDO;
$sql = "SELECT * FROM `users`";
$rs = $test->select($sql);
print_r($rs);
注意,插入语句的准备,不可以直接$pdo->prepare($sql),因为此时的$pdo已经是对象实例化之后的PDO类,而类里面没有prepare()这个函数
$pdo->dbh才相当于我们使用的$pdo
$stmt = $pdo->dbh->prepare($sql);
?>