-3

Why is my attempt to check for double votes, via the IP address, not working properly?

if ($qtype === "sc"){
                // single choice has only one select item



                // check whether user has already answered this question
                $i=0;
                $res = mysqli_query($mysqli, "SELECT ip FROM votedanswers WHERE ip = \"".$ip."\" and qID = \"".$qID."\"");

                while($obj = mysqli_fetch_object($res))
                {
                  $i = $i+1;
                }                   
                if ($i > 0){
                    echo "your vote has already been counted";
                }
                else{
                    //insert data
                    $res = mysqli_query($mysqli, "INSERT INTO votedanswers (ip, qID, qQuestion, aID) VALUES ('$ip', '$qID', '$quest', '$aID')");
                    echo "your vote has been counted";
                }   



        } else {
            echo "nope!";
        }`

MySQLI Table

Tested it a while ago and everything was fine. But now I can vote as much as I want.

Greenonline
  • 1,330
  • 8
  • 23
  • 31
SBoles
  • 1
  • 2
  • 2
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php). [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Nov 04 '18 at 17:08

1 Answers1

0

Try this:

    if ($qtype === "sc"){
            // single choice has only one select item



            // check whether user has already answered this question
            $i=0;
            $res = mysqli_query($mysqli, "SELECT ip FROM votedanswers WHERE ip = \"".$ip."\" and qID = \"".$qID."\"");

            while($obj = mysqli_fetch_assoc($res))
            {
              $i = $i+1;
            }                   
            if ($i > 0){
                echo "your vote has already been counted";
            }
            else{
                //insert data
                $res = mysqli_query($mysqli, "INSERT INTO votedanswers (ip, qID, qQuestion, aID) VALUES ('$ip', '$qID', '$quest', '$aID')");
                echo "your vote has been counted";
            }   



    } else {
        echo "nope!";
    }

Also refer to: How can I prevent SQL injection in PHP?