当前位置: 移动技术网 > IT编程>开发语言>PHP > php中mysql连接方式PDO使用详解

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

2018年07月02日  | 移动技术网IT编程  | 我要评论

pdo常用方法:

pdo::query()主要用于有记录结果返回的操作(pdostatement),特别是select操作。

pdo::exec()主要是针对没有结果集合返回的操作。如insert,update等操作。返回影响行数。
pdo::lastinsertid()返回上次插入操作最后一条id,但要注意:如果用insert into tb(col1,col2) values(v1,v2),(v11,v22)..的方式一次插入多条记录,lastinsertid()返回的只是第一条(v1,v2)插入时的id,而不是最后一条记录插入的记录id。
pdostatement::fetch()是用来获取一条记录。配合while来遍历。
pdostatement::fetchall()是获取所有记录集到一个中。
pdostatement::fetchcolumn([int column_indexnum])用于直接访问列,参数column_indexnum是该列在行中的从0开始索引值,但是,这个方法一次只能取得同一行的一列,只要执行一次,就跳到下一行。因此,用于直接访问某一列时较好用,但要遍历多列就用不上。
pdostatement::rowcount()适用于当用query("select ...")方法时,获取记录的条数。也可以用于预处理中。$stmt->rowcount();
pdostatement::columncount()适用于当用query("select ...")方法时,获取记录的列数。

注解:
1、选fetch还是fetchall?
小记录集时,用fetchall效率高,减少从数据库检索次数,但对于大结果集,用fetchall则给系统带来很大负担。数据库要向web前端传输量太大反而效率低。
2、fetch()或fetchall()有几个参数:
mixed pdostatement::fetch([int fetch_style [,int cursor_orientation [,int cursor_offset]]])
array pdostatement::fetchall(int fetch_style)

fetch_style参数:
■$row=$rs->fetchall(pdo::fetch_both); fetch_both是默认的,可省,返回关联和索引。
■$row=$rs->fetchall(pdo::fetch_assoc); fetch_assoc参数决定返回的只有关联数组。
■$row=$rs->fetchall(pdo::fetch_num); 返回索引数组
■$row=$rs->fetchall(pdo::fetch_obj); 如果fetch()则返回对象,如果是fetchall(),返回由对象组成的二维数组

复制代码 代码如下:

<?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. 捕捉错误

复制代码 代码如下:

 <?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. 事务的

复制代码 代码如下:

<?php
try{
$dbh->setattribute(pdo::attr_errmode,pdo::errmode_exception);
$dbh->begintransaction();//开启事务
$dbh->exec("insertintostaff(id,first,last)values(23,'joe','bloggs')");
$dbh->exec("insertintosalarychange(id,amount,changedate)
values(23,50000,now())");
$dbh->commit();//提交事务
}catch(exception$e){
$dbh->rollback();//错误回滚
echo"failed:".$e->getmessage();
}
?>

4. 错误处理

a. 静默模式(默认模式)

复制代码 代码如下:

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

以上就是关于php中pdo的相关用法的全部内容了,希望本文能对大家有所帮助,也希望大家能够喜欢。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网