記事一覧機能を実装する

ここから管理機能を実装していきます。
今回は、記事一覧機能の実装です。

完成後の画面

当ページの実習を行うと、以下のような記事の一覧画面が完成します。

プログラムの修正

post_list.phpを以下のように修正します。

admin/post_list.php
<?php require_once "../system/common_admin.php";?>
<?php
// データの問い合わせ
$rows_post = array(); // 配列の初期化
try {
    $stmt = $db->prepare("SELECT * FROM posts ORDER BY post_created DESC");
    $stmt->execute(); // クエリの実行
    $rows_post = $stmt->fetchAll(); // SELECT結果を二次元配列に格納
} catch (PDOException $e) {
    // エラー発生時
    exit("クエリの実行に失敗しました");
}
?>
<?php $page_title = "記事管理";?>
<?php require "header.php";?>
    <a href="post_edit.php">記事を追加する</a>
    <hr>
<?php if ($rows_post) {?>
    <table border="1" width="100%">
      <tr>
        <th></th>
        <th>タイトル</th>
        <th>本文</th>
        <th>更新日時</th>
        <th>作成日時</th>
        <th></th>
      </tr>
<?php     foreach ($rows_post as $row_post) {;?>
      <tr>
        <td><a href="post_edit.php?mode=change&post_id=<?php echo he($row_post["post_id"]);?>">編集</a></td>
        <td><?php echo he($row_post["post_title"]);?></td>
        <td><?php echo nl2br(he($row_post["post_content"]));?></td>
        <td><?php echo he($row_post["post_updated"]);?></td>
        <td><?php echo he($row_post["post_created"]);?></td>
        <td><a href="post_edit.php?mode=delete&post_id=<?php echo he($row_post["post_id"]);?>">削除</a></td>
      </tr>
<?php     }?>
    </table>
<?php }?>
<?php require "footer.php";?>

修正箇所の解説

// データの問い合わせ
$rows_post = array(); // 配列の初期化
try {
    $stmt = $db->prepare("SELECT * FROM posts ORDER BY post_created DESC");
    $stmt->execute(); // クエリの実行
    $rows_post = $stmt->fetchAll(); // SELECT結果を二次元配列に格納
} catch (PDOException $e) {
    // エラー発生時
    exit("クエリの実行に失敗しました");
}

postsテーブルからデータを取得します。

<?php if ($rows_post) {?>
    <table border="1" width="100%">
      <tr>
        <th></th>
        <th>タイトル</th>
        <th>本文</th>
        <th>更新日時</th>
        <th>作成日時</th>
        <th></th>
      </tr>

$rows_postに値がある場合に、tableの生成を行います。

<?php     foreach ($rows_post as $row_post) {;?>
      <tr>
        <td><a href="post_edit.php?mode=change&post_id=<?php echo he($row_post["post_id"]);?>">編集</a></td>
        <td><?php echo he($row_post["post_title"]);?></td>
        <td><?php echo nl2br(he($row_post["post_content"]));?></td>
        <td><?php echo he($row_post["post_updated"]);?></td>
        <td><?php echo he($row_post["post_created"]);?></td>
        <td><a href="post_edit.php?mode=delete&post_id=<?php echo he($row_post["post_id"]);?>">削除</a></td>
      </tr>
<?php     }?>

$rows_postの中身を繰り返し処理します。
「編集」をクリックした際は、mode=change&post_id=XXというパラメータを付けて編集画面を呼び出し、既存の記事を編集するモードとして動作するようにします。
「削除」をクリックした際は、mode=delete&post_id=XXというパラメータを付けて編集画面を呼び出し、既存の記事を削除するモードとして動作するようにします。

以上で管理画面の記事一覧機能が実装できました。
今回のコンテンツについては以下よりダウンロードできます。

step3-040.zip

このページをシェア Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn