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

<!DOCTYPE html>
<html lang="en">
<head>

</head>
<body>
    <?php  
      $posts = $viewModel->get("posts");
      $post_id = $viewModel->get("post_id");
    ?>
    <div class="content">
      <div class="content__all">
        <?php  
          foreach ($posts as $post) {
            echo "<h3>" . $post->title . "</h3>";
            echo "<h6 style='color: cadetblue;'>" . $post->title . "</h6>";
          }
        ?>
      </div>
      <div class="content_one">
        <h3><?php echo $post_id->title; ?></h3>
      </div>
    </div>
</body>
</html>

Last updated