【问题标题】:Voting System using Radio Buttons & Checkboxes (PHP)使用单选按钮和复选框的投票系统 (PHP)
【发布时间】:2016-05-29 12:36:34
【问题描述】:

我有三个 PHP 页面。登录、投票和投票过程。在投票页面,用户可以为候选人投票。有单选按钮和复选框。以下是投票页面的代码:

    <?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();

if (isset($_SESSION['uname'])) {
    $username = $_SESSION['uname'];
}

else {
    header('Location: login_user.php');
    die();
}
?>

<html>
<head>
    <title>Trinity University of Asia Voting System</title>
</head>
<body>
    <img src="images/tua_logo.jpg"><marquee>Practice your right to vote.</marquee><br>

    <center>
        <a href="/">Home</a> | <a href="results.php">Results</a> | <a href="logout.php">Logout</a><br>
        <h3>Cast Your Vote</h3>
        <form action="processvoting.php" method="post">
        <table cellpadding="4" border="1">
            <tr>
                <th>Position</th>
                <th>Choice 1</th>
                <th>Choice 2</th>
            </tr>
            <tr>
                <th>President</th>
                <td><input type="radio" name="president" value="pres1">&nbsp;JOHN MICHAEL KALEMBE<br>College of Business Administration</td>
                <td><input type="radio" name="president" value="pres2">&nbsp;SUZAN JOHN<br>College of Education</td>
            </tr>
            <tr>
                <th>Vice President</th>
                <td><input type="radio" name="vice_president" value="vicepres1">&nbsp;JULIUS SAMWEL<br>College of Medical Technology</td>
                <td><input type="radio" name="vice_president" value="vicepres2">&nbsp;JEUNICE MARIANO<br>College of Business Administration</td>
            </tr>
            <tr>
                <th>Secretary</th>
                <td><input type="radio" name="secretary" value="sec1">&nbsp;ANGELO CHRSTIAN DE GUZMAN<br>College of Medical Technology</td>
                <td><input type="radio" name="secretary" value="sec1">&nbsp;MICHAEL SANGA<br>College of Hospitality and Tourism Management</td>
            </tr>
            <tr>
                <th>Treasurer</th>
                <td><input type="radio" name="treasurer" value="treas1">&nbsp;MARIE DANIELLE THEREZE VALDEZ<br>College of Hospitality and Tourism Management</td>
                <td><input type="radio" name="treasurer" value="treas1">&nbsp;JEUNICE MARIANO<br>College of Business Administration</td>
            </tr>
            <tr>
                <th>Auditor</th>
                <td><input type="radio" name="auditor" value="aud1">&nbsp;KOBI TSARLZ GONZALES<br>College of Computing and Information Sciences</td>
                <td><input type="radio" name="auditor" value="aud1">&nbsp;MARIAN ENTERO<br>College of Business Administration</td>
            </tr>
            <tr>
                <th>Business Manager</th>
                <td><input type="checkbox" name="bus_manager" value="bus1">&nbsp;MICAH EDILYN TAN<br>College of Arts and Sciences</td>
                <td>N/A</td>
            </tr>
            <tr>
                <th>Public Relations Officer (PRO)</th>
                <td><input type="checkbox" name="pro" value="pro1">&nbsp;MARIBETH LIAMZON<br>College of Education</td>
                <td>N/A</td>
            </tr>
        </table>
        <input type="submit" name="submit" value="Cast Your Vote">&nbsp;&nbsp;<input type="reset" value="Reset">
    </form>
</center>
</body>
</html>

一旦用户投票,他将被重定向到投票过程页面,代码如下:

<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();

if (isset($_SESSION['uname'])) {
    $username = $_SESSION['uname'];
}

else {
    header('Location: login_user.php');
    die();
}

include 'connection.php';

if(isset($_POST['submit'])) {
    $president = $_POST['president'];
    $vicepres = $_POST['vice_president'];
    $secretary = $_POST['secretary'];
    $treasurer = $_POST['treasurer'];
    $auditor = $_POST['auditor'];
    $businessmanager = $_POST['bus_manager'];
    $pro = $_POST['pro'];

    $conn = mysqli_connect('localhost', 'root', '', 'electiondb');

    if (!$conn) {
        die("Connecton failed: " . mysqli_connect_error());
    }

    $votesql = "SELECT voted FROM student_log WHERE username = '$username'";
    $query = mysqli_query($conn, $votesql);

    while($record = mysqli_fetch_array($query)) {
          $hasvoted = $record['voted'];
        }

    if ($hasvoted == 0) {

        if ($president == '') {
            echo "You cannot leave $president blank. Please go back and try again.";;
        }
        elseif ($vicepres == '') {
            echo "You cannot leave $vicepres blank. Please go back and try again.";
        }
        elseif ($secretary == '') {
            echo "You cannot leave $secretary blank. Please go back and try again.";
        }
        elseif ($treasurer == '') {
            echo "You cannot leave $treasurer blank. Please go back and try again.";
        }
        elseif ($auditor == '') {
            echo "You cannot leave $auditor blank. Please go back and try again.";
        }
        elseif ($businessmanager == ''){
            echo "You cannot leave $businessmanager blank. Please go back and try again.";
        }
        elseif ($pro == '') {
            echo "You cannot leave $pro blank. Please go back and try again.";
        }

        else {
            switch ($president) {
                case 'pres1':
                $votepres1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'president'";
                $runpres1 = mysqli_query($conn, $votepres1);
                break;
                case 'pres2':
                $votepres2 = "UPDATE vote_log SET choice2 = choice2+1 WHERE position = 'president'";
                $runpres2 = mysqli_query($conn, $votepres2);
                break;
            }

            switch ($vicepres) {
                case 'vicepres1':
                $votevicepres1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'vice_president'";
                $runvicepres1 = mysqli_query($conn, $votevicepres1);
                break;
                case 'vicepres2':
                $votevicepres2 = "UPDATE vote_log SET choice2 = choice2+1 WHERE position = 'vice_president'";
                $runvicepres2 = mysqli_query($conn, $votevicepres2);
                break;
            }

            switch ($secretary) {
                case 'sec1':
                $votesec1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'secretary'";
                $runsec1 = mysqli_query($conn, $votesec1);
                break;
                case 'sec2':
                $votesec2 = "UPDATE vote_log SET choice2 = choice2+1 WHERE position = 'secretary'";
                $runsec2 = mysqli_query($conn, $votesec1);
                break;
            }

            switch ($treasurer) {
                case 'treas1':
                $votetreas1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'treasurer'";
                $runtreas1 = mysqli_query($conn, $votetreas1);
                break;
                case 'treas2':
                $votetreas2 = "UPDATE vote_log SET choice2 = choice2+1 WHERE position = 'treasurer'";
                $runtreas2 = mysqli_query($conn, $votetreas2);
                break;
            }

            switch ($auditor) {
                case 'aud1':
                $voteaud1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'auditor'";
                $runaud1 = mysqli_query($conn, $voteaud1);
                break;
                case 'aud2':
                $voteaud2 = "UPDATE vote_log SET choice2 = choice2+1 WHERE position = 'auditor'";
                $runaud2 = mysqli_query($conn, $voteaud2);
                break;
            }

            switch ($businessmanager) {
                case 'bus1':
                $votebus1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'business_manager'";
                $runbus1 = mysqli_query($conn, $votebus1);
                break;
            }

            switch ($pro) {
                case 'pro1':
                $votepro1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'pro'";
                $runpro1 = mysqli_query($conn, $votepro1);
                break;
            }

            $sqlforvoted = "UPDATE student_log SET voted = 1 WHERE username = '$username'";
            $processsql = mysqli_query($conn, $sqlforvoted) or die (mysqli_error($conn));
            echo "Thank you for voting. You may now logout of the system.<br><a href='logout.php'>Logout</a>";
        }
    }
    else {
        echo "You cannot vote more than once. <br><a href='logout.php'>Logout</a>";
    }
}

?>

<html>
<head>
    <title>Voting Process</title>
</head>
<body>
</body>
</html>

投票不会增加,但用户被视为“已投票”,因此用户一旦登录就无法再次投票。我唯一担心的是投票不计算在内。我的代码有问题还是我对投票数的理解不是很好?谢谢!

【问题讨论】:

  • 当你说“不计算”时,具体是什么意思?你的意思是你想更新一个存储在内存中的count,上面写着有多少人投票给“这个人”作为秘书,“这个人”投票给财务等等?
  • 在数据库中,每个候选人的所有投票计数都设置为 0,如果用户投票给候选人,我希望它增加。但它不会增加。是的,正是你说的!我认为我的 sql 代码有问题,但这是我的第三次尝试,但仍然无法正常工作
  • @Webeng 代码有一些更新!
  • 哦,你的权利哈哈,我没有向下滚动,我的错
  • 此消息是否会突然弹出?:“您不能多次投票”

标签: php html mysql voting


【解决方案1】:

我认为您的 HTML 中有一些拼写错误。在这里,选项是pres1pres2

<td><input type="radio" name="president" value="pres1"> ... </td>
<td><input type="radio" name="president" value="pres2"> ... </td>

但是在这里,两个选项都是sec1:

<td><input type="radio" name="secretary" value="sec1"> ... </td>
<td><input type="radio" name="secretary" value="sec1"> ... </td>

关于数据库交互,最好使用 PDO 和准备好的语句 - 它比大多数字符串连接方案更安全。检查此页面右侧的“相关”列 - 最有可能的问题是 this one,它很好地解释了这个主题。

无论如何,这是对您的 submit 部分的不同看法,它只是删除了所有重复。它不使用 PDO(我没有添加任何数据库代码),但至少在最终查询中没有未经过滤的用户输入——只有预定义的值:

if(isset($_POST['submit']) && !empty($_POST["submit"])) {

    if($hasvoted != 0){
        echo "You cannot vote more than once. <br><a href='logout.php'>Logout</a>";
        exit;
    }

    $positions = array(
        "president" => null, 
        "vice_president" => null,
        "secretary" => null,
        "treasurer" => null,
        "auditor" => null,
        "bus_manager" => null,
        "pro" => null
        );

    foreach (array_keys($positions) as $position)
    {
        if (!isset($_POST[$position]) || empty($_POST[$position])) {

            echo "All positions must be filled. Please try again.<br>";
            exit;
        }
        else{

            $choice = "";

            $choice_num = substr($_POST[$position], -1);

            if($choice_num == 1 || $choice_num == 2){
                $choice = "choice" . $choice_num;
            }
            else{
                echo "Error - invalid option";
                exit;
            }

            $positions[$position] = $choice;
        }

    }

    foreach (array_keys($positions) as $position)
    {
        $choice = $positions[$position];

        $sql_str = "UPDATE vote_log SET " . $choice ." = " . $choice . "+1 WHERE position = '" . $position . "'";

        // $sql_insert = mysqli_query($conn, $sql_str);

        echo $sql_str . "<br>";

    }


    echo "Thank you for voting. You may now logout of the system.<br><a href='logout.php'>Logout</a>";

}

【讨论】:

  • 它仍然没有登录到数据库:(为什么会这样?我已经放置了所有必要的连接......
  • @GeeNim 不登录,不增加或两者兼而有之?当你执行"SELECT voted FROM student_log WHERE username = '$username'"; 时,你真的在​​获取数据吗?我假设您尝试打印/回显一些数据只是为了检查您是否可以实际查询数据库。当您从 mySQL shell 手动执行 UPDATEs 和 SELECTs 时会发生什么?我们需要有关您的调试过程的输出和更多信息来确定错误。
  • 我实际上是从该查询中获取数据。一旦用户投票,我就能够获取数据并将数据更新为 1,我真正唯一关心的是投票的计数和更新
  • 我曾经遇到过这个 sql 错误 mariadb 的事情,但我能够解决这个问题。我实际上能够从我的代码中看到的唯一错误是用于实际计票的 sql 语句,其余的似乎工作得很好
  • 它登录,注销,但投票不增加
【解决方案2】:

你可以替换这个:

switch ($president) {
    case 'pres1':
    $votepres1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'president'";
    $runpres1 = mysqli_query($conn, $votepres1);
    break;
    case 'pres2':
    $votepres2 = "UPDATE vote_log SET choice2 = choice2+1 WHERE position = 'president'";
    $runpres2 = mysqli_query($conn, $votepres2);
    break;
}

有了这个:

// here you take the last char of $president (value 1 or 2) and concatenate it to "choice"
$choice = "choice".substr($president, -1);
$votepres = "UPDATE vote_log SET $choice = $choice + 1 WHERE position = 'president'";
$runpres = mysqli_query($conn, $votepres);

注意 SQL 语句中的间距。

为了防止 SQL 注入,您必须修改调用变量的语句。在这种情况下,您调用 $username 的语句(您应该调用用户 ID,而不是用户名)。 调用用户 ID,您可以在执行以下查询之前检查它是否为整数值:if (is_int($userID)) { ...do query... } else { ...do not... }

【讨论】:

  • 我实际上没有用户ID,我的表由用户的全名、用户名和密码组成
  • 好的,您应该始终将字段 ID 创建为主字段。您还可以使用 mysqli_real_escape_string 避免 SQL 注入,如下所示:$username = mysqli_real_escape_string($_SESSION['uname']);
  • 是的,我做到了。仍然不成功:(还不算数
  • 好的,我已经用新代码编辑了答案,你能试试吗?但是,为了防止 SQL 注入,我在 cmets 的代码中忘记了一个参数,这是正确的语句:$username = mysqli_real_escape_string($conn, $_SESSION['uname']);
猜你喜欢
  • 1970-01-01
  • 2012-05-02
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多