<?php
try{
$dbh = new PDO('mysql:dbname=testdb;host=localhost', 'mysql_user', 'mysql_pwd');
}catch(PDOException $e){
echo '数据库连接失败:'.$e->getMessage();
exit;
}
echo '<table border="1" align="center" width=90%>';
echo '<caption><h1>联系人信息表</h1></caption>';
echo '<tr bgcolor="#cccccc">';
echo '<th>UID</th><th>姓名</th><th>联系地址</th><th>联系电话</th><th>电子邮件</th></tr>';
$stmt = $dbh->prepare("SELECT uid,name,address,phone,email FROM contactInfo");
$stmt->execute();
$allRows = $stmt->fetchAll(PDO::FETCH_ASSOC); //以关联下标从结果集中获取所有数据
foreach($allRows as $row){ //遍历获取到的所有行数组$allRows
echo '<tr>';
echo '<td>'.$row['uid'].'</td>'; //从结果行数组中获取uid
echo '<td>'.$row['name'].'</td>'; //从结果行数组中获取name
echo '<td>'.$row['address'].'</td>'; //从结果行数组中获取address
echo '<td>'.$row['phone'].'</td>'; //从结果行数组中获取phone
echo '<td>'.$row['email'].'</td>'; //从结果行数组中获取email
echo '</tr>'; //输出每行结束标记
}
echo '</table>';
/* 以下是在fetchAll()方法中使用两个特别参数的演示示例 */
$stmt->execute(); //再次执行一个准备好的SELECT语句
$row=$stmt->fetchAll(PDO::FETCH_COLUMN, 1); //从结果集中获取第二列的所有值
echo '所有联系人的姓名:'; //输出提示
print_r($row); //输出获取到的第二列所有姓名数组