Một ví dụ đơn giản liên kiết với database (ok)
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
CREATE TABLE `posts` (
`id` int(10) UNSIGNED NOT NULL,
`title` varchar(255) NOT NULL,
`content` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `posts` (`id`, `title`, `content`) VALUES
(1, 'Title 1', 'Conent 1'),
(2, 'Title 2', 'Conent 2');
ALTER TABLE `posts`
ADD PRIMARY KEY (`id`);
ALTER TABLE `posts`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
COMMIT;INSERT INTO `posts` (`id`, `title`, `content`) VALUES (NULL, 'Title 1', 'Conent 1'), (NULL, 'Title 2', 'Conent 2');C:\xampp\htdocs\wpclidemo\models\post.php
<?php
class Post {
public $id;
public $title;
public $content;
function __construct($id, $title, $content) {
$this->id = $id;
$this->title = $title;
$this->content = $content;
}
static function all() {
$list = [];
$db = DB::getInstance();
$req = $db->query('SELECT * FROM posts');
foreach ($req->fetchAll() as $item) {
$list[] = new Post($item['id'], $item['title'], $item['content']);
}
return $list;
}
static function find($id) {
$db = DB::getInstance();
$req = $db->prepare('SELECT * FROM posts WHERE id = :id');
$req->execute(array('id' => $id));
$item = $req->fetch();
if (isset($item['id'])) {
return new Post($item['id'], $item['title'], $item['content']);
}
return null;
}
}C:\xampp\htdocs\wpclidemo\views\Home\index.php

Last updated
Was this helpful?