本文实例讲述了php使用PDO下exec()函数查询执行后受影响行数的方法。分享给大家供大家参考,具体如下:

exec()方法返回执行后受影响的行数

语法:int PDO::exec(string statement)

提示:

参数statement是要执行的SQL语句。该方法返回执行查询时受影响的行数,通常用于insert,delete和update语句中。但不能用于select查询,返回查询结果

为了验证这个提示,下面我分别对insert,delete,update,select 查询进行测试;

INSERT

try{
 $conn=new PDO("mysql:host=$servername;dbname=$dbname", $username,$password);
 $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
 $sql="INSERT INTO `hello`(`firstname`,`lastname`,`email`)values('ye','xianming','1150416034@qq.com'),
  ('xiao','hua','xiaohua@163.com')";
 $conn->exec($sql);
 echo "Insert record success";
}catch(PDOException $e){
  echo "Error:".$e->getMessage();
}

Delete

try{
 $conn=new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
 $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
 $sql="delete from hello where id=61";
 $conn->exec($sql);
 echo "delete record success";
}catch(PDOException $e){
  echo "Error".$e->getMessage();
}

Update

try{
 $conn=new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
 $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
 $sql="UPDATE hello SET firstname='xiao',lastname='ming' WHERE id='62'";
 $conn->exec($sql);
 echo "update record success";
}catch(PDOException $e){
 echo "Error".$e->getMessage();
}

Select

try{
 $conn=new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
 $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
 $sql="select * from hello";
 $query=$conn->exec($sql);
 for($i=0;$i<count($query);$i++){
  print_r($query);
 }
  echo "select record success";
}catch(PDOException $e){
  echo "Error".$e->getMessage();
}

注:上面四种查询方式,最后只有select查询不能正常执行.

更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP基于pdo操作数据库技巧总结》、《php+Oracle数据库程序设计技巧总结》、《PHP+MongoDB数据库操作技巧大全》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家PHP程序设计有所帮助。

点赞(115)

评论列表共有 0 条评论

立即
投稿
返回
顶部