<?php /** *File name: PDO.php *Created by: ShowJoy *Contact: 734578348@qq.com, xubiao522@gmail.com *Last modified: 2014-5-27 */ class User{ private $id; private $name;//这里必须注意取名必须和从数据库里返回数据的列名一致 public function getUserName(){ return $this->name; } } try{ $dsn = "mysql:dbname=test;host=localhost";// Data source name $pdo = new PDO($dsn, 'root', 'xubiao');//创建PDO对象 $res = $pdo->query('select * from users'); $res->setFetchMode(PDO::FETCH_CLASS, 'User');//记录的获取模式,将返回的记录转换成具体类的对象 while(!!$row = $res->fetch()){ //$row就是User类的对象 echo $row->getUserName(); } unset($pdo); //关闭数据库连接 }catch (PDOException $e){ echo '<p class="error">An error occurrend: '.$e->getMessage().'</p>'; } ?>