CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) CHARACTER SET utf8 DEFAULT NULL,
`mobile` varchar(11) CHARACTER SET utf8 DEFAULT NULL,
`regtime` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
Common\User.php:
<?php
namespace Common;
class User{
public $id;
public $name;
public $mobile;
public $regtime;
protected $db;
//构造方法
function __construct($id) {
$this->db = new Database\MySQLi();
$conn = $this->db->connect('127.0.0.1', 'root', '', 'test');
$res = $this->db->query("select * from user where id = {$id} limit 1");
$data = $res->fetch_assoc();
$this->id = $data['id'];
$this->name = $data['name'];
$this->mobile = $data['mobile'];
$this->regtime = $data['regtime'];
}
//析构方法
function __destruct() {
$this->db->query("update user set name = '{$this->name}', mobile = '{$this->mobile}', regtime = '{$this->regtime}' where id = {$this->id} limit 1");
}
}
Common\Databases\MySQLi.php
<?php
namespace Common\Database;
use Common\IDatabase;
class MySQLi implements IDatabase{
protected $conn;
function connect($host, $user, $passwd, $dbname){
$conn = mysqli_connect($host, $user, $passwd ,$dbname);
$this->conn = $conn;
}
function query($sql){
$res = mysqli_query($this->conn, $sql);
return $res;
}
function close(){
mysqli_close($this->conn);
}
}