您好,登錄后才能下訂單哦!
如何在PHP中實現數據對象映射模式?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
數據庫 test ,user 表結構:
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); } }
入口文件 index.php
<?php define('BASEDIR',__DIR__); //定義根目錄常量 include BASEDIR.'/Common/Loader.php'; spl_autoload_register('\\Common\\Loader::autoload'); echo '<meta http-equiv="content-type" content="text/html;charset=utf8">'; /* * 對對象屬性的操作就完成了對數據庫的操作 */ $user = new Common\User(1); //讀取數據 var_dump($user->id, $user->mobile, $user->name, $user->regtime);exit(); $user->mobile = '13800138000'; $user->name = 'Arshavin'; $user->regtime = date("Y-m-d H:i:s",time());
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。