如何检查选择查询是否提供任何数据?

时间:2016-06-22 08:43:52

标签: php mysql pdo

我制作了一个带有投票系统的小型php网站。 我使用PDO进行sql调用,但无法让它检查一个人每天不能为同一类别投票两次。

下面你找到我的php代码和sql表。

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

数据库的屏幕截图:http://prntscr.com/bjgx6w

2 个答案:

答案 0 :(得分:0)

您可以通过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)

在这里,我已经为所有条件做出了准备。

答案 1 :(得分:-1)

检查返回的行数:

$aantalRijen->rowCount() > 0