LoginSignup
0
0

More than 3 years have passed since last update.

PHP、MySQLで、Wordpressのような記事サイト制作。絞り込み、ページャー機能について

Posted at

初めまして。
phpを独学で勉強中です。

phpの投稿フォームからMySQLへ保存し、一覧で書き出したり絞り込み検索ができるシステムを構築しています。
(Wordpressのブログのイメージです。ページャー機能も付けています)

絞り込み検索とページャーの機能はとりあえず動くようになったのですが、下記問題があります。
 ・複数項目の絞り込みに対応できない。
   →現状、キーワード検索のみ
 ・ページャーが、絞り込みをかけてもテーブル内すべてのデータを含んでしまう。
  2ページ目に移動すると絞り込みが解除されてしまう。

こちらどの様に改善するかお分かりになる方いらっしゃれば、ご教授いただけますと幸いです。
お手数おかけしますが、よろしくお願いいたします。

▼MySQL
テーブル名: shop
カラム1: ID(連番)
カラム2: s_name(テキスト)

▼HTML(検索フォーム)

<form action="search.php" method="post">
    <dl><dt>キーワード検索</dt>
        <dd><input type="text" name="sea_name"></dd></dl>
    <dl><dd><input id="send" type="submit" value="送信する"></dd></dl>
</form>

▼php(一覧表示)

<?php
$sea_name = $_POST['sea_name'];

$user = 'user';
$pass = 'pass';
$dsn = 'mysql:host=localhost;dbname=db';
$shop = new PDO($dsn, $user, $pass);

if (isset($_GET['page'])) {
$page = (int)$_GET['page'];
} else {
$page = 1;
}

if ($page > 1) {
// 例:2ページ目の場合は、『(2 × 10) - 10 = 10』
$start = ($page * 3) - 3;
} else {
$start = 0;
}

if(!empty($sea_name)) {
$sea_name = addslashes($sea_name);
$where = "s_name REGEXP '$sea_name' &";
}

if(!empty($where)) {
$where = substr($where, 0, -1);
$where = "WHERE " . $where;
}

$posts = $shop->prepare("
SELECT  *
FROM shop 
{$where}
ORDER BY id DESC
LIMIT {$start}, 3
");

$posts->execute();
$posts = $posts->fetchAll(PDO::FETCH_ASSOC);
?>

    <p>検索条件</p>
    <p>フリーワード:<?php echo $sea_name; ?></p>
            <p>検索結果</p>
    <?php 
    foreach ($posts as $post) {
        echo "
    <li>
    <h3>{$post['s_name']}</h3>
    </li>
    "
    ;}
    ?>
    </ul>
<?php 
$page_num = $shop->prepare("
    SELECT COUNT(*) id
    FROM shop
");
$page_num->execute();
$page_num = $page_num->fetchColumn();

$pagination = ceil($page_num / 3);

for ($x=1; $x <= $pagination ; $x++) { ?>
<a href="?page=<?php echo $x ?>"><?php echo $x; ?></a>
<?php } // End of for ?>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0