<?php $dbh = new PDO('mysql:dbname=testdb;host=localhost', 'mysql_user', 'mysql_pwd'); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = "SELECT name, phone, email FROM contactInfo WHERE departmentId='D01'"; try { //执行SELECT查询,并返回PDOstatement对象 $pdostatement = $dbh->query($query); echo "一共从表中获取到".$pdostatement->rowCount()."条记录: "; foreach ($pdostatement as $row) { //从PDOstatement对象中遍历结果 echo $row['name'] . " "; //输出从表中获取到的联系人的名字 echo $row['phone'] . " "; //输出从表中获取到的联系人的电话 echo $row['email'] . " "; //输出从表中获取到的联系人的电子邮件 } } catch (PDOException $e) { echo $e->getMessage(); }