0

I have three PHP pages. Login, Vote, and Vote Process. In the vote page, the user may vote for the candidates. There are radio buttons and checkboxes. Here are the codes for the Vote page:

    <?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>

Once the user votes, he will be redirected to the Vote Process page and this is the code:

<?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>

The votes do not increment but the user is deemed as 'voted' therefore the user cannot vote again once logged in. My only concern is that the votes are not counting. Is there something wrong with my codes or is my understanding of vote counts not that great? Thank you!

Gee Nim
  • 11
  • 7
  • 1
    when you say "not counting", what do you mean specifically? You mean that you want to update a `count` somewhere stored in memory that says how many people voted for "this person" for secretary, "this person" for treasurer, etc? – Webeng May 29 '16 at 12:43
  • in the database, all the vote counts for each candidate are set to 0, and if a user votes for the candidates, i'd want it to increment. But it doesn't increment. Yes, exactly what you said! I think there's something wrong with my sql codes but it's my third try and it still isn't working – Gee Nim May 29 '16 at 12:46
  • @Webeng there are some updates in the code! – Jeff May 29 '16 at 12:49
  • ohhh your right lol, I didn't scroll down, my bad – Webeng May 29 '16 at 12:50
  • is this message poping up by any chance?: "You cannot vote more than once" – Webeng May 29 '16 at 12:52
  • Yes. If you cast your vote as a user, your user data will be updated and it will say that you have voted. So if you log in again "You cannot vote more than once" shows up but if you look at the database containing the votes all the candidates still have 0. – Gee Nim May 29 '16 at 12:53
  • Have you done the usual debugging steps? var_dump($_POST), error_reporting on, checking for mysqli-errors? – Jeff May 29 '16 at 12:54
  • @GeeNim There's a lot of repetition in your code and possibly a risk of SQL injection as well. Check out PDO, parameter binding, and prepared statements for database interactions - it can fix both issues. – jDo May 29 '16 at 12:59
  • @Jeff i did an error detection but it shows up as a blank page. – Gee Nim May 29 '16 at 13:04
  • @jDo: what do you suggest that i do? I'll read up on that then – Gee Nim May 29 '16 at 13:05

2 Answers2

0

You could replace this:

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;
}

With this:

// 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);

Note spacing in SQL statement.

To prevent SQL Injection you have to modify the statements where a variable is called. In this case the statements where you call $username (you should call the user ID, instead the username). Calling the user ID you can simply check if it's an integer value before do the query as follow: if (is_int($userID)) { ...do query... } else { ...do not... }

codable
  • 11
  • 4
  • i don't have a user id actually, my table consists of user's full name, the username, and the password – Gee Nim May 29 '16 at 13:24
  • Ok, you should always create the field ID as primary field. You can also avoid SQL Injection using the mysqli_real_escape_string as follow: `$username = mysqli_real_escape_string($_SESSION['uname']);` – codable May 29 '16 at 14:10
  • yes i did. still unsuccessful :( it still isnt counting – Gee Nim May 29 '16 at 22:48
  • Ok, I've edited the answer with new code, could you try it? However, in order to prevent SQL Injection, I forgot one parameter to my code in comments, this is the right statement: `$username = mysqli_real_escape_string($conn, $_SESSION['uname']);`. – codable May 30 '16 at 07:59
0

I think you have some typos in your HTML. Here, the options are pres1 and pres2:

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

but here, both options are sec1:

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

Regarding the database interactions, it would be better to use PDO and prepared statements - it's safer than most string concatenation schemes. Check the "related" column to the right on this page - the top question is most likely this one that explains this topic well.

Anyway, here's a different take on your submit section that simply removes all the repetition. It doesn't use PDO (I didn't add any database code) but at least there's no unfiltered user input in the final query - only predefined values:

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>";

}
jDo
  • 3,962
  • 1
  • 11
  • 30
  • It still does not log into the database :( why could this be? I've placed all the necessary connections... – Gee Nim May 29 '16 at 23:11
  • @GeeNim does not log in, does not increment or both? Are you actually getting data when you execute `"SELECT voted FROM student_log WHERE username = '$username'";`? I assume you've tried printing/echoing some data just to check that you can actually query the database. What happens when you do manual `UPDATE`s and `SELECT`s from a mySQL shell? We need output and more info on your debugging process to pin down the error. – jDo May 29 '16 at 23:26
  • im actually getting data from that query. i was able to get data and update the data into 1 once the user has voted, my actual and only concern is the counting and the updating of the votes – Gee Nim May 29 '16 at 23:30
  • i once had this sql error mariadb thing but i was able to fix that. the only error i was actually able to see from my code is my sql statements for the actual counting of the votes, the rest seem to work pretty fine – Gee Nim May 29 '16 at 23:31
  • it logs in, logs out, but the votes do not increment – Gee Nim May 29 '16 at 23:31
  • @GeeNim Ok, assuming that you can manually update and increment the values from a shell, are you sure the update statements are being executed? Add echo statements in your switch case block to make sure that they're executed. – jDo May 29 '16 at 23:43