// 数据库配置文件, db_config.php
$db_server = "localhost";
$db_user = "root";
$db_pwd = "";
$db_name = "table";
?>
<?
// class_user.php
class UserInfo{
private $userName; //属性,用户名
private $userPSW ; //属性,用户密码
private $userAge ; //属性,用户年龄
private $userGrade ; //属性,用户级别
private $userInfo; //存储数据库返回信息的数组变量.
public function __construct($name){
require_once("db_config.php"); //包含配置信息.
$sql = "select * from e_user where username='$name' "; //书写sql
$conn = mysql_pconnect($db_server, $db_user, $db_pwd);//建立mysql连接
$my_db = mysql_select_db($db_name,$conn);//选择数据库
$result = mysql_query($sql, $conn); // 执行查询语句
$this->userInfo = mysql_fetch_array($result); //返回查询结果到数组
mysql_close($conn); //关闭数据库连接
$this->getInfo(); //调用传递信息的方法.
}
// 获取信息传递给属性的方法
private function getInfo(){
$this->userName = $this->userInfo["username"];
$this->userPSW = $this->userInfo["userpsw"];
$this->userAge = $this->userInfo["userage"];
$this->userGrade = $this->userInfo["usergrade"];
}
//返回每个属性的public 方法.
public function getUserName(){
return $this->userName;
}
public function getUserPSW(){
return $this->userPSW;
}
public function getUserAge(){
return $this->userAge;
}
public function getUserGrade(){
return $this->userGrade;
}
}
?>
<? //viewuser.php
require_once("class_user.php");
$user = new UserInfo("Tom"); //创建一个user对象.
$username = $user->getUserName(); //分别调用方法取得数据
$userpsw = $user->getUserPSW();
$userage = $user->getUserAge();
$usergrade = $user->getUserGrade();
echo "your name is ".$username."<br>"; //输出数据
echo "your password is ".$userpsw."<br>" ;
echo "your age is ".$userage."<br>" ;
echo "your grade is ".$usergrade."<br>" ;
?>