我是PHP/MySQL和整个网站设计的新手。我正在建立一个预定义用户可以投票的网站。我有一个包含用户列表的数据库。我正在努力避免重复投票。我读过你可以阻止IP地址或使用cookie,但我试图使用另一种方法。避免重复投票
在我的数据库名为'用户'我有三列 - 用户名,密码和标志。 标志的默认值为0.一旦用户投票,我将该特定用户的标志设置为1.现在,如果用户试图再次投票,我想检查数据库中标志的值。如果它是0,我会将他发送给“感谢您投票”页面,并更新我创建的另一个数据库,称为结果,以记录每个候选人收到的投票数。如果不是,我带他到另一页说:“你已经投了票。”到目前为止,一切正常,除非我不知道如何读取数据库中的标志值并使用它的if条件。
这是我到目前为止有:
<?php
$host="localhost"; // Host name
$username="dbxxxxx"; // Mysql username
$password="password"; // Mysql password
$db_name="dbxxxxx_users"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$user = $_COOKIE["details"]; //cookie details has the username the user used to log in
$SQL = "SELECT flag FROM users WHERE Username='$user'";
$flag = mysql_query($SQL); //no clue what's happening here. Just trying random stuff
$db_field = mysql_fetch_assoc($flag);
if($db_field==0) //checking the value of flag in the database
{
mysql_query("UPDATE result SET Votes=Votes+1 //if flag in database = 0
WHERE Name='Candidate1'"); //updates result for candidate1 if the user voted for 1
$user = $_COOKIE["details"]; //reading the cookie again. can be omitted.
mysql_query("UPDATE users SET flag=1 //changing flag to 1 so user cannot vote again
WHERE Username='$user'");
header("location: http://www.lithuaniavote.com/thankyou.html");
}
else //flag != 1 or user has already voted
{
header("location: http://www.lithuaniavote.com/alreadyvoted.html");
}
?>
PS:此代码更改为0的标志1在数据库中。但是,if条件有问题。即使标志为1,我也能够投票,这表明我已经投了票,换句话说,它从未将我带到已投票页面。
我会猜测问题是你的SQL更新标志的语法错误,但是你的代码有比这更糟糕的问题。您正在使用未转义的用户输入构建SQL查询。 – Cairnarvon
调试你的代码:[如何在PHP中获取有用的错误消息?](http://stackoverflow.com/q/845021/1409082) – Jocelyn
你也在混合'$ db_field'和'$ fdb_field'。 – icktoofay