0%

[技能檢定]題組二 步驟18 製作前台問卷投票功能

投票功能的製作,我們利用網址傳遞id的方式讓主題的資訊可以被帶到投票頁面,再據依製作相關的內容。

  1. 我們先在類別撰寫一個方法,這個方法會取得一個主題資料及對應的選項資料
    /Controller/Que.php
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    function subject($id){
    //根據帶入的id取得主題資料
    $subject=$this->find($id);

    //根據主題的id取得所有的選項
    $options=$this->all(['subject_id'=>$id]);

    //將選項資料放到主題資料陣列中
    $subject['options']=$options;

    //回傳主題資料含選項
    return $subject;
    }
  2. 建立 /view/front/vote.php 檔案,並撰寫投票功能
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    <?php
    //根據網址的id參數來取得投票主題及選項內容
    $subject=$Que->subject($_GET['id']);
    ?>
    <fieldset>
    <legend>目前位置:首頁 > 問卷調查 > <?=$subject['text'];?></legend>
    <h3><?=$subject['text'];?></h3>
    <form action="./api/vote.php" method="post">
    <?php
    foreach($subject['options'] as $opt){
    ?>
    <p>
    <input type="radio" name="opt" value="<?=$opt['id'];?>">
    <span><?=$opt['text'];?></span>
    </p>
    <?php } ?>

    <input type="submit" value="我要投票">
    </form>
    </fieldset>

  1. 撰寫投票紀錄程式,這邊我們會根據投票的選項再去找出主題,並讓主題的投票數也跟著加1,這樣就可以在投票時同時計算總票數
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    include_once "../base.php";
    //根據表單資料取出被選擇的選項資料
    $opt=$Que->find($_POST['opt']);

    //票數資料加1
    $opt['vote']++;

    //更新選項資料
    $Que->save($opt);

    //根據選項資料的subject_id欄位來取得主題資料
    $subject=$Que->find($opt['subject_id']);
    //主題票數資料加1
    $subject['vote']++;

    //更新主題資料
    $Que->save($subject);

    to("../index.php?do=result&id={$subject['id']}");