此例子是MVC的简单应用, 要达到的效果如下:
用户列表:
姓名 | 年龄 | 学历 | 兴趣 | 出生地 | 账号创建时间 | 操作 |
keen | 20 | 高中 | 篮球,足球 | 广东 | 2016-11-08 10:00:31 | 删除 |
andi | 30 | 本科 | 乒乓球 | 上海 | 2016-11-22 10:00:55 | 删除 |
ddddddd | 40 | 初中 | 台球 | 广州 | 2016-11-10 12:20:49 | 删除 |
eeeeeee | 34 | 大专 | 慢跑 | 深圳 | 2016-11-15 12:21:26 | 删除 |
当前用户总数: 4
一.设计表
create table if not exists tab_users(
id int auto_increment primary key,
name varchar(50) not null,
age int default 18,
edu varchar(20),
hobby varchar(200),
born_place varchar(20),
create_time datetime
);
执行, 自己填入数据
二.相关类
1. 基本类, 已经构造了对数据库访问的链接资源
BaseModel.class.php
<?php
include './MySQLDB.class.php';
class BaseModel{
// 存储数据库工具类实例
protected $db = null;
function __construct(){
$config = array(
'host' => 'localhost',
'port' => 3306,
'user' => 'root',
'pwd' => '123456',
'charset' => 'utf8',
'dbname' => 'db1'
);
$this->db = MySQLDB::GetInstance($config);
}
}
?>
2.用户模型类, 封装了获取用户相关数据的方法
UserModel.class.php
<?php
/*
用户模型
*/
include './BaseModel.class.php';
class UserModel extends BaseModel{
function getAllUsers(){
$sql = "select * from tab_users";
return $this->db->getRows($sql);
}
function getUsersCount(){
$sql = "select count(*) from tab_users";
return $this->db->getOneData($sql);
}
function delUserById($id){
$sql = "delete from tab_users where id = '$id'";
return $this->db->exec($sql);
}
}
?>
3.单例工厂类: 通过类名,获取唯一实例
ModelFactory.class.php
<?php
/*
单例工厂类
*/
class ModelFactory{
static $models = array(); // 用于存储各个模型的唯一实例
static function M($className){
if(!isset(static::$models[$className]) || // 不存在
!(static::$models[$className] instanceof $className)){ // 不是其实例
static::$models[$className] = new $className();
}
return static::$models[$className];
}
}
?>
4.控制器: 先调用模型,获取数据.然后再载入视图,显示数据
showAllUserController.php
<?php
/*
显示所有用户的控制器
*/
header("content-type:text/html;charset=utf8"); // 设置输出的字符串编码为utf8
include './UserModel.class.php';
include './ModelFactory.class.php';
// 判断动作
if(!empty($_GET['act']) && $_GET['act'] == 'del'){
$id = $_GET['id'];
$obj = ModelFactory::M("UserModel");
$obj->delUserById($id);
echo "<p style='color:red;'>删除数据成功!</p>";
}
// 获取数据
$user_obj = ModelFactory::M("UserModel");
$data1 = $user_obj->getAllUsers();
/*
echo "<pre>";
print_r($data1);
echo "</pre>";
*/
$data2 = $user_obj->getUsersCount();
// 载入视图文件, 显示数据
include './showAllUserView.html';
?>
5.视图
showAllUserView.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-cn"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <title>网页标题</title> <meta name="keywords" content="关键字列表" /> <meta name="description" content="网页描述" /> <link rel="stylesheet" type="text/css" href="" /> <style type="text/css"> </style> <script type="text/javascript"> function del_confirm() { console.log('进入 confirm 方法中...'); return window.confirm("你真的要删除吗?"); } </script> </head> <body> 用户列表: <table border="1"> <tr> <td>姓名</td> <td>年龄</td> <td>学历</td> <td>兴趣</td> <td>出生地</td> <td>账号创建时间</td> <td>操作</td> </tr> <?php foreach($data1 as $rec){ ?> <tr> <td><?php echo $rec['name']; ?></td> <td><?php echo $rec['age']; ?></td> <td><?php echo $rec['edu']; ?></td> <td><?php echo $rec['hobby']; ?></td> <td><?php echo $rec['born_place']; ?></td> <td><?php echo $rec['create_time']; ?></td> <td> <a href="?act=del&id=<?php echo $rec['id']; ?>" οnclick="return del_confirm()">删除</a> </td> </tr> <?php } ?> </table> 当前用户总数: <?php echo $data2; ?> </body> </html>
ps:
MySQLDB.class.php
<?php /* 设计一个类:mysql数据库操作类 设计目标: 1,该类一实例化,就可以自动连接上mysql数据库; 2,该类可以单独去设定要使用的连接编码(set names XXX) 3,该类可以单独去设定要使用的数据库(use XXX); 4,可以主动关闭连接; */ class MySQLDB{ private $link = null; // 用于存储成功链接后的资源 // 属性, 存储链接数据库的基本信息 private $host; private $port; private $user; private $pwd; private $charset; private $dbname; // 1)私有化构造方法 private function __construct($config){ // 保存链接的基本信息 $this->host = !empty($config['host']) ? $config['host'] : "localhost"; $this->port = !empty($config['port']) ? $config['port'] : "3306"; $this->user = !empty($config['user']) ? $config['user'] : "root"; $this->pwd = !empty($config['pwd']) ? $config['pwd'] : ""; $this->charset = !empty($config['charset']) ? $config['charset'] : "utf8"; $this->dbname = !empty($config['dbname']) ? $config['dbname'] : "mysql"; // 链接数据库 $this->link = mysql_connect("{$this->host}:{$this->port}", "$this->user", "$this->pwd") or die("链接失败"); // 设定编码 //mysql_query("set names {$config['charset']}"); $this->setCharset($config['charset']); // 设定要使用的数据库名 //mysql_query("use {$config['dbname']}"); $this->selectDB($config['dbname']); } // 2)单例, 存储唯一实例 private static $instance = null; // 3)静态方法,获取唯一实例 static function GetInstance($config){ //if(!isset(self::$instance)){ // ==>等价于 if(!(self::$instance instanceof self)){ // 更常用 self::$instance = new self($config); // 创建并保存起来 } return self::$instance; } // 4)私有化克隆方法 private function __clone(){} // 可设定要使用的编码 function setCharset($charset){ mysql_query("set names $charset", $this->link); } // 可设定要使用的数据库 function selectDB($dbname){ mysql_query("use $dbname", $this->link); } // 可关闭数据库链接 function closeDB(){ mysql_close($this->link); } // 执行 sql 语句,进行错误处理,并返回结果 private function query($sql){ $result = mysql_query($sql, $this->link); if($result === false){ // 失败处理 echo "sql语句执行失败,请参考如下信息:"; echo "<br />错误代码: " . mysql_errno(); echo "<br />错误信息: " . mysql_error(); echo "<br />错误语句: " . $sql; die(); } return $result; } // 执行一条 增删改 sql语句,返回真或假 function exec($sql){ $result = $this->query($sql); return true; } // 执行一条 sql 语句,返回一行记录 function getOneRow($sql){ $result = $this->query($sql); $rec = mysql_fetch_assoc($result); // 提前销毁结果集,否则需要等待页面结束才能自动销毁 mysql_free_result($result); return $rec; } // 执行一条 sql 语句,返回多行记录 function getRows($sql){ $result = $this->query($sql); $arr = array(); while($rec = mysql_fetch_assoc($result)){ $arr[] = $rec; // 二维数组 } mysql_free_result($result); return $arr; } // 执行一条 sql 语句,直接返回一个结果 // 类似于: select count(*) as c from user_list function getOneData($sql){ $result = $this->query($sql); $rec = mysql_fetch_row($result); $data = $rec[0]; mysql_free_result($result); return $data; } } ?>
生活不止眼前, 还有诗和远方. end.