:::
11-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); } -
由於打算直接在函數中把呈現列表時,樣板需要的變數直接傳到樣板,因此,直接用 global 宣告 $smarty 物件,讓他可以在函數中使用。
-
撈資料時,我們以活動日期為排序依據,從新排到舊(日期大到小)
-
此時的 $actions 是一個二維陣列,第一個索引為第N筆資料,第二個索引則為某一筆資料的各個欄位。
-
從現實考量,這裡暫時不限制enable=1以及報名截止日的問題。
二、在樣板中呈現列表
- 我們可以讓樣板,根據 $op 值來引入不同樣板,列如:
{if $op=="regist"} {include file='regist_form.tpl'} {elseif $op=="list_action"} {include file='list_action.tpl'} {else} {$content} {/if} -
也就是當執行列出活動時,就引入 list_action.tpl 作為主內容,而 list_action.tpl 只專心做列出活動的列表即可。
-
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>
三、練習
- 「從現實考量,這裡暫時不限制enable=1以及報名截止日的問題。」請思考一下,是怎樣的考量?這樣的作法是否適當?會不會有什麼問題?有無更好作法?
11. 重新調整流程