<?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(); }