1、数据库抽象层pdo

(1)PDO(php data object)扩展类库为php访问数据库定义了轻量级的、一致性的接口它可以支持mysql,postgresql,oracle,mssql等多种数据库

(2). PDO的安装

编辑php.ini文件:

extension=php_pdo.dll

extension=php_pdo_mysql.dll

重启apache服务:

httpd k restart

打开phpinfo.php查看是否有pdo

 

2、创建pdo对象

Oracle

/*连接如果失败,使用异常处理模式进行捕获 */

try{

$dbh = newPDO("OCI:dbname=accounts;charset=UTF-8", "scott","tiger");

}catch(PDOException$e) {

echo "数据库连接失败: " .$e->getMessage();

}

Mysql

$dsn ='mysql:dbname=testdb;host=127.0.0.1'; //连接MySQL数据库的DSN

$user = 'dbuser';//MySQL数据库的用户名

$password ='dbpass'; //MySQL数据库的密码

try {

$dbh = newPDO($dsn, $user, $password);

} catch(PDOException $e) {

echo '数据库连接失败: ' . $e->getMessage();

}

 

Php.ini配置文件中[pdo]下在加入下面文字

Pdo.dsn.ssw=”mysql:host=localhosot;dbname=malldb”;

try {

$dbh = new PDO(ssw,root, sswqzx);

} catch(PDOException $e) {

echo '数据库连接失败: ' . $e->getMessage();

}

 

//设置持久连接的选项数组作为最后一个参数,可以一起设置多个元素

$opt =array(PDO::ATTR_PERSISTENT => true);

try {

$db = newPDO('mysql:host=localhost;dbname=test''dbuser''passwrod',$opt);

} catch(PDOException $e) {

echo "数据库连接失败: " .$e->getMessage();

}

 

3PDO与连接有关的选项

         try {

                   $pdo=new  PDO("mysql:host=localhost;dbname=malldb","root","123456",array(PDO::ATTR_AUTOCOMMIT=>false,PDO::ATTR_PERSISTENT=>1 ));

         }catch(PDOException $e) {

                   echo "数据库连接失败:".$e->getMessage();

                   exit;

         }

//var_dump($pdo);

//      $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,false);

 

         echo "
PDO
是否关闭自动提交功能:".$pdo->getAttribute(PDO::ATTR_AUTOCOMMIT);

         echo "
当前PDO的错误处理的模式:". $pdo->getAttribute(PDO::ATTR_ERRMODE);

         echo "
表字段字符的大小写转换: ".$pdo->getAttribute(PDO::ATTR_CASE);

         echo "
与连接状态相关特有信息: ".$pdo->getAttribute(PDO::ATTR_CONNECTION_STATUS);

         echo "
空字符串转换为SQLnull". $pdo->getAttribute(PDO::ATTR_ORACLE_NULLS);

         echo "
应用程序提前获取数据大小:".$pdo->getAttribute(PDO::ATTR_PERSISTENT);

         echo "
与数据库特有的服务器信息:".$pdo->getAttribute(PDO::ATTR_SERVER_INFO);

         echo "
数据库服务器版本号信息:".$pdo->getAttribute(PDO::ATTR_SERVER_VERSION);

         echo "
数据库客户端版本号信息:".$pdo->getAttribute(PDO::ATTR_CLIENT_VERSION);

 

4PDO的错误处理模式

/*

setAttribute();

PDO::ATTR_ERRMODE;

1、默认的错误模式(不提示、我们看到问题、被忽视)

2、警告模式:PDO::ERRMODE_WARNING

3、异常的模式:PDO::ERRMODE_EXCEPTION

*/

 

try(

//创建对象

$pdo = newPDO("mysql:host=localhost;dbname=malldb","root","sswqzx");

//设置错误使用异常的模式

$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

)catch(PDOException $e){

         echo"数据库链接失败".$e->getMessage();

         exit;

}

 

try(

//使用PDO中的方法执行语句

$affected_rows = $pdo ->exec("delete from hello");

)catch(PDOException $e){

echo "错误".$e->getMessage();

}

 

5、使用PDO执行SQL语句

代码1

/*

PDO中执行SQL语句的方法有二个主要的:

1exec() 用来处理非结果集的: insert updatedelete create ....

返回影响的函数

2query() 用来处理有结果集的语句: select descshow

 

set naees utf8;

$pdo -> query("set namesutf8");

$pdo -> exec("set namesutf8");

*/

 

try{

//创建对象

$pdo = new PDO("mysql:host=localhost;dbname=malldb","root","sswqzx");

//设置错误使用异常的模式

$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

}catch(PDOException $e){

         echo"数据库链接失败".$e->getMessage();

         exit;

}

 

try{

//使用PDO中的方法执行语句

$affected_rows = $pdo ->exec("insert into user(name,pass,sex,age,email)values('aa','bb','cc','20','[email protected]')");

echo $affected_rows."
";

echo $pdo->lastinsertid();

}catch(PDOException $e){

echo "错误".$e->getMessage();

}

代码2

try{

$dbh = newPDO('mysql:dbname=testdb;host=localhost', 'mysql_user', 'mysql_pwd');

}catch(PDOException$e){

exit('数据库连接失败:'.$e->getMessage());

}

$query = UPDATE contactInfo SET phone=15801680168 where name=‘高某某’”;

//使用exec()方法可以执行INSERTUPDATEDELETE

$affected =$dbh->exec($query);

if($affected){

echo '数据表contactInfo中受影响的行数为:'.$affected;

}else{

print_r($dbh->errorInfo());

}

代码3

$dbh = newPDO('mysql:dbname=testdb;host=localhost', 'mysql_user', 'mysql_pwd');

$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

$query =

"SELECT name,phone, email FROM contactInfo WHERE departmentId='D01'";

try {

//执行SELECT查询,并返回PDOstatement对象              

$pdostatement =$dbh->query($query);

echo "一共从表中获取到".$pdostatement->rowCount()."条记录:\n";

foreach($pdostatement as $row) {//PDOstatement对象中遍历结果

echo $row['name'] ."\t"; //输出从表中获取到的联系人的名字

echo $row['phone']. "\t"; //输出从表中获取到的联系人的电话

echo $row['email']. "\n";//输出从表中获取到的联系人的电子邮件

}

} catch(PDOException $e) {

echo$e->getMessage();

}

6PDO事务处理

MySQL的事务处理

事务:将多条sql操作(增删改)作为一个操作单元,要

么都成功,要么都失败。

MySQL对事务的支持:

被操作的表必须是innoDB类型的表(支持事务)

MySQL常用的表类型:MyISAM(非事务)增删改速度快、

InnodB(事务型)安全性高

更改表的类型为innoDB类型

mysql> altertable stu engine=innodb;

Query OK, 29 rowsaffected (0.34 sec)

Records: 29Duplicates: 0 Warnings: 0

mysql> showcreate table stu\G; //查看表结构

事务处理

Mysql> set autocommit = 0;

mysql>start transaction;

Mysql>commit;

Mysql>roolback;

7、构建事务处理的应用程序

开启一次事务:

$pdo->beginTransaction();

提交一次事务:

$pdo->commit();

回滚一次事务:

$pdo->rollback();

注意如下设置:

1.$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,0);

2.$pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,1);

代码:

/*

 * PDO中执行SQL语句的方法有两个主要的:

 *

 *    1.  exec()   用来处理非结果集的  insert update deletecreate ....

 *

 *      返回影响的函数

 *

 *      如果是插入语句可以使用lastinsertid()方法获取最后自动插入id

 *

 *

 *    2.  query()   用来处理有结果集的语句  select   desc show

 *

 *   返回来的是 PDOStatement类的对象,再通过这个类的方法,获取结果。也可以直接foreach遍历获取结果(但不常用)

 *

 *    setnames utf8;

 *

 *   $pdo -> query("set names utf8");

 *   $pdo -> exec("set names utf8");

 */

 

         try{

                   //创建对象

                   $pdo= new PDO("mysql:host=localhost;dbname=malldb", "root","123456");

                   //设置错误使用异常的模式

                   $pdo-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                   //关闭自动提交

                   $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 0);

         }catch(PDOException$e) {

                   echo"数据库连接失败:".$e->getMessage();

                   exit;

         }

 

 

         try{

                   //开启一个事务

                   $pdo-> beginTransaction();

 

                   $price= 50;

                   //妹子转出50

                   $affected_rows= $pdo-> exec("update demo set ye=ye-{$price} where id=1");

 

                   if($affected_rows> 0) {

                            echo"妹子转出{$price}元成功!
";

                   }else {

                            thrownew PDOException("妹子转出失败!
");

                   }

 

                   //张三会收到50

                   $affected_rows= $pdo-> exec("update demo set ye=ye+{$price} where id=3");

 

                   if($affected_rows){

                            echo"张三收到{$price}元成功!";

                   }else{

                            thrownew PDOException("张三收入失败!
");

                   }

 

        

                   echo"交易成功!
";

 

                  //提交以上的操作

                   $pdo->commit();     

 

         }catch(PDOException$e) {

                   echo"错误:".$e->getMessage();

                   echo"交易失败!
";

                   //撤销所有操作

                   $pdo-> rollback();

         }

 

         //运行完成以后, 最后开启自动提交

         $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT, 1);

8、使用PDO准备语句并执行语句

得到pdo预处理对象的方法:

$sql=select * from user order by id;

$sth=$pdo->prepare($sql);

以上代码中的$sth即为预处理对象

PDO中参数式的SQL语句有两种(预处理sql)

1.insert intostu(id,name) value(?,?); //?号式(适合参数少的)

2.insert intostu(id,name) value(:id,:name);//别名式(适合参数多的)

代码1

         try{

                   //创建对象

                   $pdo= new PDO("mysql:host=localhost;dbname=malldb", "root","123456");

                   //设置错误使用异常的模式

                   $pdo-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                   $pdo-> query("set names utf8");

         }catch(PDOException$e) {

                   echo"数据库连接失败:".$e->getMessage();

                   exit;

         }

 

 

         try{

                   //给数据库管理系统并直接执行

                   //$pdo-> query("select * from users");

                  

                   //只是将这个语句放到服务器上(数据库管理系统)上, 编写后等待,没有执行

                   $stmt= $pdo -> prepare("insert into users(name, pass, age, sex, email)values(?, ?, ?, ?, ?)");

 

                   //绑定参数(?),将问号和一个变量关联起来

                   $stmt-> bindParam(1, $name);

                   $stmt-> bindParam(2, $pass);

                   $stmt-> bindParam(3, $age);

                   $stmt-> bindParam(4, $sex);

                   $stmt-> bindParam(5, $email);

 

                   //给变量一个值, 就会给准好的语句中的对应?一个值

                   $name= "admin";

                   $pass= "hello";

                   $age= 100;

                   $sex= "nnn";

                   $email= "[email protected]";

                   //执行上面在数据库系统中准备好的语句

                   $stmt-> execute();

        

 

         }catch(PDOException$e) {

                   echo"错误:".$e->getMessage();

         }

 

代码2:

         try {

                   //创建对象

                   $pdo= new PDO("mysql:host=localhost;dbname=malldb", "root","123456");

                   //设置错误使用异常的模式

                   $pdo-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                   $pdo-> query("set names utf8");

         }catch(PDOException$e) {

                   echo"数据库连接失败:".$e->getMessage();

                   exit;

         }

 

 

         try{

                   //给数据库管理系统并直接执行

                   //$pdo-> query("select * from users");

                  

                   //只是将这个语句放到服务器上(数据库管理系统)上, 编写后等待,没有执行

                   $stmt= $pdo -> prepare("insert into users(name, pass, age, sex, email)values(:name, :pass, :age, :sex, :email)");

 

                   //绑定参数(?),将问号和一个变量关联起来

                   $stmt-> bindParam("name", $name, PDO::PARAM_STR);

                   $stmt-> bindParam("pass", $pass, PDO::PARAM_STR);

                   $stmt-> bindParam("age", $age, PDO::PARAM_INT);

                   $stmt-> bindParam("sex", $sex, PDO::PARAM_STR);

                   $stmt-> bindParam("email", $email, PDO::PARAM_STR);

 

                   //给变量一个值, 就会给准好的语句中的对应?一个值

                   $name= "admin1";

                   $pass= "hello1";

                   $age= 1001;

                   $sex= "nnn1";

                   $email= "[email protected]";

                   //执行上面在数据库系统中准备好的语句

                   $stmt-> execute();

        

 

 

                  //给变量一个值, 就会给准好的语句中的对应?一个值

                   $name= "admin2";

                   $pass= "hello2";

                   $age= 1002;

                   $sex= "nnn2";

                   $email= "[email protected]";

                   //执行上面在数据库系统中准备好的语句

                   $stmt-> execute();                      

         }catch(PDOException$e) {

                   echo"错误:".$e->getMessage();

         }

代码3

         try{

                   //创建对象

                   $pdo= new PDO("mysql:host=localhost;dbname=malldb", "root","123456");

                   //设置错误使用异常的模式

                   $pdo-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                   $pdo-> query("set names utf8");

         }catch(PDOException$e) {

                   echo"数据库连接失败:".$e->getMessage();

                   exit;

         }

 

 

         try{

                   //给数据库管理系统并直接执行

                   //$pdo-> query("select * from users");

                  

                   //只是将这个语句放到服务器上(数据库管理系统)上, 编写后等待,没有执行

              //  $stmt = $pdo -> prepare("insert into users(name, pass, age, sex,email) values(:name, :pass, :age, :sex, :email)");

                $stmt = $pdo -> prepare("insertinto users(name, pass, age, sex, email) values(?, ? ,?, ?, ?)");

 

 

                $stmt -> execute(array("jone",'123456', 18, 'nv', '[email protected]'));       

                $stmt -> execute(array("jone2",'123456', 18, 'nv', '[email protected]'));       

                $stmt -> execute(array("jone22",'123456', 18, 'nv', '[email protected]'));       

 

 

         }catch(PDOException$e) {

                   echo"错误:".$e->getMessage();

         }

 

代码4

         try{

                   //创建对象

                   $pdo= new PDO("mysql:host=localhost;dbname=malldb", "root","123456");

                   //设置错误使用异常的模式

                   $pdo-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                   $pdo-> query("set names utf8");

         }catch(PDOException$e) {

                   echo"数据库连接失败:".$e->getMessage();

                   exit;

         }

 

 

         try{

                   //给数据库管理系统并直接执行

                   //$pdo-> query("select * from users");

                  

                   //只是将这个语句放到服务器上(数据库管理系统)上, 编写后等待,没有执行

$stmt = $pdo -> prepare("insertinto users(name, pass, age, sex, email) values(:name, :pass, :age, :sex,:email)");

// $stmt = $pdo -> prepare("insertinto users(name, pass, age, sex, email) values(?, ? ,?, ?, ?)");

$stmt ->execute(array("name"=>"feng","pass"=>"abc123#", "age"=>28,"sex"=>"nan","email"=>"[email protected]"));       

    

         }catch(PDOException$e) {

                   echo"错误:".$e->getMessage();

         }

 

代码5

 

         try{

                   //创建对象

                   $pdo= new PDO("mysql:host=localhost;dbname=malldb", "root","123456");

                   //设置错误使用异常的模式

                   $pdo-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                   $pdo-> query("set names utf8");

         }catch(PDOException$e) {

                   echo"数据库连接失败:".$e->getMessage();

                   exit;

         }

 

 

         try{

                   //给数据库管理系统并直接执行

                   //$pdo-> query("select * from users");

                  

                   //只是将这个语句放到服务器上(数据库管理系统)上, 编写后等待,没有执行

                 $stmt = $pdo -> prepare("insertinto users(name, pass, age, sex, email) values(:name, :pass, :age, :sex,:email)");

               // $stmt = $pdo ->prepare("insert into users(name, pass, age, sex, email) values(?, ? ,?, ?,?)");

 

 

                $stmt -> execute($_GET);               

               

 

         }catch(PDOException$e) {

                   echo"错误:".$e->getMessage();

         }

 

9PDO的预处理查询

代码1

         try{

                   //创建对象

                   $pdo= new PDO("mysql:host=localhost;dbname=malldb", "root","123456");

                   //设置错误使用异常的模式

                   $pdo-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                   $pdo-> query("set names utf8");

         }catch(PDOException$e) {

                   echo"数据库连接失败:".$e->getMessage();

                   exit;

         }

 

 

         try{

                  

                   $stmt= $pdo -> prepare("select id, name, age, sex, email from users where id> ? and id < ?");

                   $stmt-> execute(array(500, 800));

 

        

                   foreach($stmtas $row) {

                            print_r($row);

                            echo'
';

                   }

 

                   //mysql_fetch_array()   mysql_fetch_rows  mysql_fetch_array()

/*

                   echo'

';

                   while(list($id,$name, $age, $sex, $email) = $stmt -> fetch(PDO::FETCH_NUM)) {

                            echo'

';

                            echo'

';

                            echo'

';

                            echo'

';

                            echo'

';

                            echo'

';

                            echo'

';

                   }

 

                   echo'

'.$id.' '.$name.' '.$age.' '.$sex.' '.$email.'
';

 */           

 

         }catch(PDOException$e) {

                   echo"错误:".$e->getMessage();

         }

代码2

 

try {

                   //创建对象

                  $pdo = newPDO("mysql:host=localhost;dbname=malldb", "root","123456");

                   //设置错误使用异常的模式

                   $pdo-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                   $pdo-> query("set names utf8");

         }catch(PDOException$e) {

                   echo"数据库连接失败:".$e->getMessage();

                   exit;

         }

 

 

         try{

                  

                   $stmt= $pdo -> prepare("select id, name, age, sex, email from users where id> ? and id < ?");

                   $stmt-> execute(array(500, 800));

 

 

                   //可以设置结果的模式, 以下的代码使用fetch()fetchAll()都是使用这个方面设置的数组的格式

                   $stmt-> setFetchMode(PDO::FETCH_NUM);

 

 

                   echo'

';

 

                   print_r($stmt->fetchAll());

 

                   echo'

';

 

                   //mysql_fetch_array()   mysql_fetch_rows mysql_fetch_array()

/*

                   echo'

';

                   while(list($id,$name, $age, $sex, $email) = $stmt -> fetch(PDO::FETCH_NUM)) {

                            echo'

';

                            echo'

';

                            echo'

';

                            echo'

';

                            echo'

';

                            echo'

';

                            echo'

';

                   }

 

                   echo'

'.$id.' '.$name.' '.$age.' '.$sex.' '.$email.'
';

 */           

 

         }catch(PDOException$e) {

                   echo"错误:".$e->getMessage();

         }

 

代码:

         try{

                   //创建对象

                   $pdo= new PDO("mysql:host=localhost;dbname=malldb", "root","123456");

                   //设置错误使用异常的模式

                   $pdo-> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

                   $pdo-> query("set names utf8");

         }catch(PDOException$e) {

                   echo"数据库连接失败:".$e->getMessage();

                   exit;

         }

 

 

         try{

                  

                   $stmt= $pdo -> prepare("insert into users(name, pass, age, sex,email)values(?, ? ,? ,? ,?)");

                   $stmt-> execute(array('111', '222', 333, '444', '555'));

 

                   //获取数据结果中的行数, 或如果是影响函数的语句执行则获取的是影响行数

                   echo$stmt->rowCount();

 

                   echo'
';

                   //如何获取最后一个自动增涨的ID?

                   echo$pdo -> lastInsertId();

         }catch(PDOException$e) {

                   echo"错误:".$e->getMessage();

         }