<?php try{ $dbh = new PDO('mysql:dbname=testdb;host=localhost', 'mysql_user', 'mysql_pwd'); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); }catch(PDOException $e){ echo '数据库连接失败:'.$e->getMessage(); exit; } //声明一个SELECT查询,从表contactInfo中获取D01部门的四个字段的信息 $query = "SELECT uid, name, phone, email FROM contactInfo WHERE departmentId='D01'"; try { $stmt = $dbh->prepare($query); //准备声明好的一个查询 $stmt->execute(); //执行准备好的查询 $stmt->bindColumn(1, $uid); //通过列位置偏移数绑定变量$uid $stmt->bindColumn(2, $name); //通过列位置偏移数绑定变量$name $stmt->bindColumn('phone', $phone); //绑定列名称到变量$phone上 $stmt->bindColumn('email', $email); //绑定列名称到变量$email上 while ($stmt->fetch(PDO::FETCH_BOUND)) { //fetch()方法传入特定的参数遍历 echo $uid."t".$name."t".$phone."t".$email."n"; //输出自动将列值赋给对应变量的值 } } catch (PDOException $e) { echo $e->getMessage(); }