:::

11-1 列出所有活動

一、讀出所有資料

  1. 在 index.php 新增函數 list_action()
    //列出所有活動
    function list_action()
    {
        global $db, $smarty;
    
        $sql    = "SELECT * FROM `actions` order by action_date desc";
        $result = $db->query($sql);
        if (!$result) {
            throw new Exception($db->error);
        }
        $actions = [];
        while ($values = $result->fetch_assoc()) {
            $actions[] = $values;
        }
        $smarty->assign('actions', $actions);
    }
  2. 由於打算直接在函數中把呈現列表時,樣板需要的變數直接傳到樣板,因此,直接用 global 宣告 $smarty 物件,讓他可以在函數中使用。

  3. 撈資料時,我們以活動日期為排序依據,從新排到舊(日期大到小)

  4. 此時的 $actions 是一個二維陣列,第一個索引為第N筆資料,第二個索引則為某一筆資料的各個欄位。

  5. 從現實考量,這裡暫時不限制enable=1以及報名截止日的問題。

二、在樣板中呈現列表

  1. 我們可以讓樣板,根據 $op 值來引入不同樣板,列如:
    {if $op=="regist"}
      {include file='regist_form.tpl'} 
    {elseif $op=="list_action"}
      {include file='list_action.tpl'}
    {else}
      {$content}
    {/if}
  2. 也就是當執行列出活動時,就引入 list_action.tpl 作為主內容,而 list_action.tpl 只專心做列出活動的列表即可。

  3. list_action.tpl 的內容為:

    <h2>活動列表</h2>
    <table class="table table-hover table-striped">
      <thead>
        <tr class="info">
          <th>活動日期</th>
          <th>活動名稱</th>
          <th>報名截止日</th>
          <th>功能</th>
        </tr>
      </thead>
      <tbody>
      {foreach $actions as $action}
          <tr>
            <td>{$action.action_date}</td>
            <td><a href="index.php?action_id={$action.action_id}">{$action.title}</a></td>
            <td>{$action.end_date}</td>
            <td></td>
          </tr>
      {/foreach}
      </tbody>
    </table>
    

三、練習

  1. 「從現實考量,這裡暫時不限制enable=1以及報名截止日的問題。」請思考一下,是怎樣的考量?這樣的作法是否適當?會不會有什麼問題?有無更好作法?

 


:::

書籍目錄

展開 | 闔起

https%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D27%26tbdsn%3D734

計數器

今天: 3152315231523152
昨天: 3176317631763176
總計: 7452584745258474525847452584745258474525847452584