PHP系列(十二)數據庫抽象層pdo


1、數據庫抽象層pdophp

(1)PDO(php data object)擴展類庫爲php訪問數據庫定義了輕量級的、一致性的接口它能夠支持mysql,postgresql,oracle,mssql等多種數據庫mysql

(2). PDO的安裝sql

編輯php.ini文件:數據庫

extension=php_pdo.dllapache

extension=php_pdo_mysql.dll數組

重啓apache服務:安全

httpd k restart服務器

打開phpinfo.php查看是否有pdooracle

 

2、建立pdo對象ide

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 "<br>PDO是否關閉自動提交功能:".$pdo->getAttribute(PDO::ATTR_AUTOCOMMIT);

         echo "<br>當前PDO的錯誤處理的模式:". $pdo->getAttribute(PDO::ATTR_ERRMODE);

         echo "<br>表字段字符的大小寫轉換: ".$pdo->getAttribute(PDO::ATTR_CASE);

         echo "<br>與鏈接狀態相關特有信息: ".$pdo->getAttribute(PDO::ATTR_CONNECTION_STATUS);

         echo "<br>空字符串轉換爲SQLnull". $pdo->getAttribute(PDO::ATTR_ORACLE_NULLS);

         echo "<br>應用程序提早獲取數據大小:".$pdo->getAttribute(PDO::ATTR_PERSISTENT);

         echo "<br>與數據庫特有的服務器信息:".$pdo->getAttribute(PDO::ATTR_SERVER_INFO);

         echo "<br>數據庫服務器版本號信息:".$pdo->getAttribute(PDO::ATTR_SERVER_VERSION);

         echo "<br>數據庫客戶端版本號信息:".$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','ee@qq.com')");

echo $affected_rows."<br>";

echo $pdo->lastinsertid();

}catch(PDOException $e){

echo "錯誤".$e->getMessage();

}

代碼2

<?php

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

<?php

$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);

代碼:

<?php

/*

 * 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}元成功!<br>";

                   }else {

                            thrownew PDOException("妹子轉出失敗!<br>");

                   }

 

                   //張三會收到50

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

 

                   if($affected_rows){

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

                   }else{

                            thrownew PDOException("張三收入失敗!<br>");

                   }

 

        

                   echo"交易成功!<br>";

 

                  //提交以上的操做

                   $pdo->commit();     

 

         }catch(PDOException$e) {

                   echo"錯誤:".$e->getMessage();

                   echo"交易失敗!<br>";

                   //撤銷全部操做

                   $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= "aaa@bbb.com";

                   //執行上面在數據庫系統中準備好的語句

                   $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= "aaa@bbb.com1";

                   //執行上面在數據庫系統中準備好的語句

                   $stmt-> execute();

        

 

 

                  //給變量一個值, 就會給準好的語句中的對應?一個值

                   $name= "admin2";

                   $pass= "hello2";

                   $age= 1002;

                   $sex= "nnn2";

                   $email= "aaa@bbb.com2";

                   //執行上面在數據庫系統中準備好的語句

                   $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', 'aa@bb.com'));       

                $stmt -> execute(array("jone2",'123456', 18, 'nv', 'aa@bb.com'));       

                $stmt -> execute(array("jone22",'123456', 18, 'nv', 'aa@bb.com'));       

 

 

         }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"=>"aaa@bbb.com"));       

    

         }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'<br>';

                   }

 

                   //mysql_fetch_array()   mysql_fetch_rows  mysql_fetch_array()

/*

                   echo'<table border="1" width=800>';

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

                            echo'<tr>';

                            echo'<td>'.$id.'</td>';

                            echo'<td>'.$name.'</td>';

                            echo'<td>'.$age.'</td>';

                            echo'<td>'.$sex.'</td>';

                            echo'<td>'.$email.'</td>';

                            echo'</tr>';

                   }

 

                   echo'</table>';

 */           

 

         }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'<pre>';

 

                   print_r($stmt->fetchAll());

 

                   echo'</pre>';

 

                   //mysql_fetch_array()   mysql_fetch_rows mysql_fetch_array()

/*

                   echo'<table border="1" width=800>';

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

                            echo'<tr>';

                            echo'<td>'.$id.'</td>';

                            echo'<td>'.$name.'</td>';

                            echo'<td>'.$age.'</td>';

                            echo'<td>'.$sex.'</td>';

                            echo'<td>'.$email.'</td>';

                            echo'</tr>';

                   }

 

                   echo'</table>';

 */           

 

         }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'<br>';

                   //如何獲取最後一個自動增漲的ID?

                   echo$pdo -> lastInsertId();

         }catch(PDOException$e) {

                   echo"錯誤:".$e->getMessage();

         }

相關文章
相關標籤/搜索