0

I made a small php site with a voting system in it. I make my sql calls with PDO but can't get it working to check that a person can't vote twice a day for the same category.

Below you find my php code and sql table.

<?php
   header("Expires: Tue, 01 Jan 2000 00:00:00 GMT");
   header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
   header("Cache-Control: no-store, no-cache, must-revalidate,max-age=0");
   header("Cache-Control: post-check=0, pre-check=0", false);
   header("Pragma: no-cache");


   session_start();
   $user = $_SESSION['username'];

   try {
      $db = new PDO('mysql:host=localhost;dbname=xxxxxxxx',"xxxxxxxxx", "xxxxxxxxxx");
   }catch (PDOException $e){
      echo $e->getMessage();
   }

   $aantalRijen = $db->query("SELECT gebruiker FROM stem WHERE UPPER(gebruiker) = '$user' AND UPPER(categorie)='dick' AND datum = CURDATE()");


   $sql = "INSERT INTO stem (categorie, naam, commentaar, datum, gebruiker)
   VALUES('dick','$_POST[naam]','$_POST[commentaar]',CURDATE(), '$user')";




   if( $aantalRijen > 0 ) {
     echo nl2br("U heeft al een stem uitgebracht \n");
     echo "<script>setTimeout(\"location.href = 'index.php';\",1500);    </script>";

    }
     else {
       $results = $db->exec($sql);
       echo "Stem succesvol uitgebracht!";
       echo "<script>setTimeout(\"location.href = 'index.php';\",1500);   </script>";

       }

       $results = NULL;
       $aantalRijen = NULL;
       $db = NULL;
?>

Screenshot of the database: http://prntscr.com/bjgx6w

2 Answers2

0

You can Do in single query by WHERE

INSERT INTO stem (categorie, naam, commentaar, datum, gebruiker)
  VALUES('dick','$_POST[naam]','$_POST[commentaar]',CURDATE(), '$user')
 WHERE NOT EXISTS 
  (SELECT * FROM stem WHERE categorie = dick' AND naam = $_POST[naam] AND commentaar = $_POST[commentaar] AND datum = CURDATE() AND gebruiker = $user)

Here i have made for all condition.

Gopalakrishnan
  • 957
  • 8
  • 19
-1

Check the number of rows returned:

$aantalRijen->rowCount() > 0
Pinke Helga
  • 6,378
  • 2
  • 22
  • 42