php中mysql连接方式PDO使用详解(2)


$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT); //不显示错误
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);//显示警告错误,并继续执行
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);//产生致命错误,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); 当$sql 中变量可以用$dbh->quote($params); //转义字符串的数据
$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 [建议用,同时可以用添加、修改、删除]

复制代码 代码如下:


<?php
$dbh->prepare($sql); 产生了个PDOStatement对象

PDOStatement->bindParam()

PDOStatement->execute();//可以在这里放绑定的相应变量
?>

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(); 
 } 
?>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/ea33dc1d0edfc7aea287042e8ba11ba1.html