欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

php mysql PDO 查詢操作的實(shí)例詳解

 更新時(shí)間:2017年09月23日 09:12:21   投稿:lqh  
這篇文章主要介紹了php mysql PDO 查詢操作的實(shí)例詳解的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下

php mysql PDO 查詢操作的實(shí)例詳解

<?php 
$dbh = new PDO('mysql:host=localhost;dbname=access_control', 'root', '');  
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
$dbh->exec('set names utf8');  
/*添加*/ 
//$sql = "INSERT INTO `user` SET `login`=:login AND `password`=:password";  
$sql = "INSERT INTO `user` (`login` ,`password`)VALUES (:login, :password)"; $stmt = $dbh->prepare($sql); $stmt->execute(array(':login'=>'kevin2',':password'=>''));  
echo $dbh->lastinsertid();  
/*修改*/ 
$sql = "UPDATE `user` SET `password`=:password WHERE `user_id`=:userId";  
$stmt = $dbh->prepare($sql);  
$stmt->execute(array(':userId'=>'7', ':password'=>'4607e782c4d86fd5364d7e4508bb10d9'));  
echo $stmt->rowCount();  
/*刪除*/ 
$sql = "DELETE FROM `user` WHERE `login` LIKE 'kevin_'"; //kevin%  
$stmt = $dbh->prepare($sql);  
$stmt->execute();  
echo $stmt->rowCount();  
/*查詢*/ 
$login = 'kevin%';  
$sql = "SELECT * FROM `user` WHERE `login` LIKE :login";  
$stmt = $dbh->prepare($sql);  
$stmt->execute(array(':login'=>$login));  
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){    
 print_r($row);  
}  
print_r( $stmt->fetchAll(PDO::FETCH_ASSOC));  
?> 

1 建立連接

<?php 
$dbh=newPDO('mysql:host=localhost;port=3306; dbname=test',$user,$pass,array( 
PDO::ATTR_PERSISTENT=>true 
)); 
?> 

持久性鏈接PDO::ATTR_PERSISTENT=>true

2. 捕捉錯(cuò)誤

<?php 
try{ 
$dbh=newPDO('mysql:host=localhost;dbname=test',$user,$pass); 
 
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); 
 
$dbh->exec("SET CHARACTER SET utf8"); 
$dbh=null; //斷開連接 
}catch(PDOException$e){ 
print"Error!:".$e->getMessage()."<br/>"; 
die(); 
} 
?> 

3. 事務(wù)的

<?php 
try{ 
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); 
 
$dbh->beginTransaction();//開啟事務(wù) 
$dbh->exec("insertintostaff(id,first,last)values(23,'Joe','Bloggs')"); 
$dbh->exec("insertintosalarychange(id,amount,changedate) 
values(23,50000,NOW())"); 
$dbh->commit();//提交事務(wù) 
 
}catch(Exception$e){ 
$dbh->rollBack();//錯(cuò)誤回滾 
echo"Failed:".$e->getMessage(); 
} 
?> 

4. 錯(cuò)誤處理

a. 靜默模式(默認(rèn)模式)

$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT); //不顯示錯(cuò)誤
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);//顯示警告錯(cuò)誤,并繼續(xù)執(zhí)行
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);//產(chǎn)生致命錯(cuò)誤,PDOException
<?php 
try{   
 $dbh = new PDO($dsn, $user, $password);   
 $sql = 'Select * from city where CountryCode =:country';   
 $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);   
 $stmt = $dbh->prepare($sql);   
 $stmt->bindParam(':country', $country, PDO::PARAM_STR);   
 $stmt->execute();   
 while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {    
 print $row['Name'] . "/t";   
 }  
}  // if there is a problem we can handle it here  
catch (PDOException $e) {   
 echo 'PDO Exception Caught. ';   
 echo 'Error with the database: <br />';   
 echo 'SQL Query: ', $sql;   
 echo 'Error: ' . $e->getMessage();  
}  
?> 

1. 使用 query()

<?php 
$dbh->query($sql); 當(dāng)$sql 中變量可以用$dbh->quote($params); //轉(zhuǎn)義字符串的數(shù)據(jù) 
 
$sql = 'Select * from city where CountryCode ='.$dbh->quote($country);  
foreach ($dbh->query($sql) as $row)  {   
 print $row['Name'] . "/t";   
 print $row['CountryCode'] . "/t";   
 print $row['Population'] . "/n";  
}  
?> 

2. 使用 prepare, bindParam和 execute [建議用,同時(shí)可以用添加、修改、刪除]

<?php 
$dbh->prepare($sql); 產(chǎn)生了個(gè)PDOStatement對(duì)象 
 
PDOStatement->bindParam() 
 
PDOStatement->execute();//可以在這里放綁定的相應(yīng)變量 
?> 

3. 事物

<?php  
 try {  
 $dbh = new PDO('mysql:host=localhost;dbname=test', 'root', '');  
 $dbh->query('set names utf8;');  
 $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
 $dbh->beginTransaction();  
 $dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('mick', 22);");  
 $dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('lily', 29);");  
 $dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('susan', 21);");  
 $dbh->commit();  
 } catch (Exception $e) {  
 $dbh->rollBack();  
 echo "Failed: " . $e->getMessage();  
 }  
?>  

PDO常用方法:

PDO::query()主要用于有記錄結(jié)果返回的操作(PDOStatement),特別是select操作。
PDO::exec()主要是針對(duì)沒有結(jié)果集合返回的操作。如insert,update等操作。返回影響行數(shù)。
PDO::lastInsertId()返回上次插入操作最后一條ID,但要注意:如果用insert into tb(col1,col2) values(v1,v2),(v11,v22)..的方式一次插入多條記錄,lastinsertid()返回的只是第一條(v1,v2)插入時(shí)的ID,而不是最后一條記錄插入的記錄ID。
PDOStatement::fetch()是用來獲取一條記錄。配合while來遍歷。
PDOStatement::fetchAll()是獲取所有記錄集到一個(gè)中。
PDOStatement::fetchcolumn([int column_indexnum])用于直接訪問列,參數(shù)column_indexnum是該列在行中的從0開始索引值,但是,這個(gè)方法一次只能取得同一行的一列,只要執(zhí)行一次,就跳到下一行。因此,用于直接訪問某一列時(shí)較好用,但要遍歷多列就用不上。
PDOStatement::rowcount()適用于當(dāng)用query("select ...")方法時(shí),獲取記錄的條數(shù)。也可以用于預(yù)處理中。$stmt->rowcount();
PDOStatement::columncount()適用于當(dāng)用query("select ...")方法時(shí),獲取記錄的列數(shù)。

注解:

1、選fetch還是fetchall?

小記錄集時(shí),用fetchall效率高,減少?gòu)臄?shù)據(jù)庫(kù)檢索次數(shù),但對(duì)于大結(jié)果集,用fetchall則給系統(tǒng)帶來很大負(fù)擔(dān)。數(shù)據(jù)庫(kù)要向WEB前端傳輸量太大反而效率低。

2、fetch()或fetchall()有幾個(gè)參數(shù):

mixed pdostatement::fetch([int fetch_style [,int cursor_orientation [,int cursor_offset]]])
array pdostatement::fetchAll(int fetch_style)

fetch_style參數(shù):

■$row=$rs->fetchAll(PDO::FETCH_BOTH); FETCH_BOTH是默認(rèn)的,可省,返回關(guān)聯(lián)和索引。
■$row=$rs->fetchAll(PDO::FETCH_ASSOC); FETCH_ASSOC參數(shù)決定返回的只有關(guān)聯(lián)數(shù)組。
■$row=$rs->fetchAll(PDO::FETCH_NUM); 返回索引數(shù)組
■$row=$rs->fetchAll(PDO::FETCH_OBJ); 如果fetch()則返回對(duì)象,如果是fetchall(),返回由對(duì)象組成的二維數(shù)組

如有疑問請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論