//登入 function login() { global $db; $email = clean_var('email', 'Eamil', FILTER_VALIDATE_EMAIL); $pass = clean_var('pass', '密碼'); $sql = "SELECT * FROM `users` where `email`='{$email}'"; $result = $db->query($sql); if (!$result) { throw new Exception($db->error); } $data = $result->fetch_assoc(); if (password_verify($pass, $data['pass'])) { $_SESSION['group'] = $data['group']; $_SESSION['name'] = htmlspecialchars($data['name'], ENT_QUOTES); $_SESSION['uid'] = $data['uid']; $_SESSION['email'] = htmlspecialchars($data['email'], ENT_QUOTES); //抓取該使用者已報名的活動編號 $sql = "SELECT action_id FROM `signups` where `uid`='{$data['uid']}'"; if (!$result2 = $db->query($sql)) { throw new Exception($db->error); } $_SESSION['uid_signup'] = []; while (list($action_id) = $result2->fetch_row()) { $_SESSION['uid_signup'][] = $action_id; } } else { throw new Exception("登入失敗!"); } }
我們將活動編號都放入 $_SESSION['uid_signup'] 陣列中
另外,讀取資料庫的迴圈中若還有讀取資料庫迴圈,其 $result 記得改名,否則第一個迴圈的 $result 會被 第二個迴圈的 $result 給取代。
由於第二個迴圈只抓了一個欄位,故改用 $result2->fetch_row() 來抓,並利用 list() 做指派,把值放到 $action_id 中。
//登出 function logout() { unset($_SESSION['group']); unset($_SESSION['name']); unset($_SESSION['uid']); unset($_SESSION['email']); unset($_SESSION['uid_signup']); }
//報名 function signup($action_id) { global $db; $uid = $_SESSION['uid']; $sql = "INSERT INTO `signups` ( `action_id`, `uid`, `signup_date`) VALUES ('{$action_id}', '{$uid}', NOW())"; if (!$db->query($sql)) { throw new Exception($db->error); } $_SESSION['uid_signup'][] = $action_id; }
{if $group=="admin"} <a href="javascript:delete_action({$action.action_id})" class="btn btn-danger btn-xs">刪除</a> <a href="admin.php?action_id={$action.action_id}" class="btn btn-warning btn-xs">修改</a> {elseif $group=="user"} {if $action.action_id|in_array:$smarty.session.uid_signup} <a href="index.php?action_id={$action.action_id}" class="btn btn-danger btn-xs">取消報名</a> {else} <a href="index.php?op=signup&action_id={$action.action_id}" class="btn btn-primary btn-xs">我要報名</a> {/if} {/if}
我們利用smarty的變數修飾器,直接使用 php 的 in_array() 函數來判斷目前此活動編號有無在 $_SESSION['uid_signup'] 陣列中
<div class="text-center"> {if $group=="admin"} <a href="javascript:delete_action({$action.action_id})" class="btn btn-danger ">刪除</a> <a href="admin.php?action_id={$action.action_id}" class="btn btn-warning">修改</a> {elseif $group=="user"} {if $action.action_id|in_array:$smarty.session.uid_signup} <a href="index.php?action_id={$action.action_id}" class="btn btn-danger btn-lg">取消報名</a> {else} <a href="index.php?op=signup&action_id={$action.action_id}" class="btn btn-primary btn-lg">我要報名</a> {/if} {/if} </div>