duanfu1945 2015-01-18 12:23
浏览 14

如何使用PHP和MySQL多次阻止一个用户名完成调查?

I've made a simple survey. Successfully filling and put it into a database table. Now the problem is how to prevent the username complete the survey more than once? Username is taken from the session. I've tried my own code here, but it didn't work :

<?php 
session_start();
include_once('config.php');

$username       = $_SESSION['username'];
$ask1           = $_POST['ask1'];
$ask2           = $_POST['ask2'];
$ask3           = $_POST['ask3'];
$ask4           = $_POST['ask4'];

$query = mysql_query("insert into survey values('', '$username', '$ask1', '$ask2', '$ask3', '$ask4')"); 


if ($query) {
        // success
        echo" <script language='JavaScript'> alert ('Thankyou for your participation');</script>";
        echo '<script language="JavaScript"> window.location.href ="home.php";</script>';
} else {
    echo "SELECT username FROM survey WHERE username='".$_SESSION['username']."'";
    $dup = mysql_query("SELECT username FROM survey WHERE username='".$_SESSION['username']."'");
        if(mysql_num_rows($dup) >0){
            echo"<script language='JavaScript'> alert ('You've filled out the survey!');</script>";
        echo '<script language="JavaScript"> window.location.href ="home.php" </script>';
        } else {
    // fail
     echo" <script language= 'JavaScript'> alert ('Failed to complete the survey'); </script>";
     echo '<script language="JavaScript"> window.location.href ="survey.php";</script>';
}}
?>

so what is the best solution for the problem like this? Thankyou in advance for you who want to help me. Thankyou once again.

  • 写回答

1条回答 默认 最新

  • dtjwov4984 2015-01-18 12:39
    关注

    In your code the problem is in the logic : You insert the new row and check afterwards if there is a row with the current username. Obviously you have to check first.

    You show the code when you are saving the result of the survey. But in fact, you should check twice.

    1. Before you display the form to the user, you have to check if he already filled it before.

    2. Upon saving : not only test in PHP if there isn't a double. Define a unique index on the column username in your table, and you are guaranteed to never have a duplicate, even if your checks failed.

    This is how to create a unique index :

    alter table survey add unique index (username);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line