blog-app/core/controllers/Search.php

40 lines
1.4 KiB
PHP
Raw Normal View History

2021-09-16 20:27:51 +08:00
<?php
namespace Controllers;
class Search
{
public function show($keyword, $page = '1')
{
$db = db();
$keyword = urldecode($keyword);
$offset = ($page >= 1) ? ($page - 1) : 0;
$offset *= 10;
$sql = 'SELECT * FROM posts WHERE title LIKE ? ' .
'ORDER BY create_at DESC LIMIT ?,10';
$query = $db->prepare($sql);
$query->bindValue(1, '%' . preg_quote($keyword) . '%');
$query->bindValue(2, $offset, \PDO::PARAM_INT);
$query->execute();
$posts = $query->fetchAll(\PDO::FETCH_CLASS, 'Core\\Record');
$offset += 10;
$query->bindValue(2, $offset, \PDO::PARAM_INT);
$query->execute();
$next = $query->fetchAll(\PDO::FETCH_CLASS, 'Core\\Record');
$sql = 'SELECT id, keyword, COUNT(id) AS num_of_posts FROM (' .
'tags JOIN post_tag ON id=tag_id) GROUP BY id ORDER BY keyword';
$query = $db->prepare($sql);
$query->execute();
$tags = $query->fetchAll(\PDO::FETCH_CLASS, 'Core\\Record');
$is_last = count($next) == 0 ? true : false;
return view('post.index', [
'keyword' => $keyword,
'posts' => $posts,
'tags' => $tags,
'page' => $page,
'is_last' => $is_last,
'pager_uri' => preg_replace('/\/\d+$/', '', $_SERVER['REQUEST_URI'])
]);
}
}