本文实例讲述了php使用PDO下exec()函数查询执行后受影响行数的方法。分享给大家供大家参考,具体如下:
exec()
方法返回执行后受影响的行数。
语法:int PDO::exec(string statement)
提示:
参数statement是要执行的SQL语句。该方法返回执行查询时受影响的行数,通常用于insert,delete和update语句中。但不能用于select查询,返回查询结果。
为了验证这个提示,下面我分别对insert,delete,update,select 查询进行测试;
INSERT
1
2
3
4
5
6
7
8
9
10
|
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
1
2
3
4
5
6
7
8
9
|
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
1
2
3
4
5
6
7
8
9
|
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
1
2
3
4
5
6
7
8
9
10
11
12
|
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程序设计有所帮助。