我目前正在构建一个下载平台,在该平台中,用户接收一个随机代码,并使用它访问mp3进行下载,最多可下载三次。我使用Python生成了一个随机代码列表,并将它们导入到一个SQL表中,其中关联的电子邮件地址有一个空列,使用计数默认为0。我写了以下PHP脚本,以便将电子邮件与特定的代码相关联,并将其添加到计数中,以便下载最多可以访问三次。
$email = $_POST["email"];
$email = stripslashes($email);
$uniqueCode = $_POST["uniqueCode"];
$uniqueCode = stripslashes($uniqueCode);
// check that all fields are filled
if($uniqueCode=="" || $email=="")
apologize("Please fill out all fields.");
// check to make sure that the e-mail is valid
if (verifyEmail($email) == FALSE)
apologize("Please enter a valid e-mail address.");
// check if uniqueCode input is alphanumeric
if (verifyCode($uniqueCode) == FALSE)
apologize("Download codes are alphanumeric.");
// check to see if unique code is correct
$sql = mysql_query("SELECT * FROM wd009 where uniqueCode='$uniqueCode'");
$result = mysql_fetch_array($sql);
if($sql==FALSE)
{
apologize("Your download code is invalid. Please try again");
}
// only allow users with less than 3 downloads to proceed
else if ($result['count'] <= 3) {
if ($result['email'] == ""){
mysql_query("UPDATE wd009 SET email='$email', count=1 WHERE uniqueCode='$uniqueCode'");
apologize("added email");
}
else if ($result['email'] != $email)
apologize("different email from record!!");
else if ($result['email'] == $email){
mysql_query("UPDATE wd009 SET count=count+1 WHERE uniqueCode='$uniqueCode'");
apologize("updated the count!");
}
else
apologize("Your download code is used up!"); 显然,我在上面使用了一些没有包含在代码中的函数,但是我已经检查了所有这些函数,它们都不应该干扰MySQL查询。值得注意的是,道歉后立即退出()。当我在表单中输入正确的代码时,它就可以正常工作并更新SQL数据库。但是,只要下载代码输入是字母数字的,表单就会接受它,即使字符串与表中的任何字符串都不匹配。也就是说,无论输入是什么,mysql_query都会返回一个资源。我已经检查了数据库连接,但由于当下载代码正确时,表也会正确更新,所以这似乎不是问题所在。
我尝试了所有我能想到的方法来调试它,但是我真的被搞糊涂了。如果您能提供任何帮助,我们将不胜感激!
发布于 2012-06-19 09:19:28
正如您在手册中看到的,对于有效的查询,mysql_query总是返回一个资源,因此您需要更改逻辑并计算它返回的行数,而不是mysql_query的结果。
除此之外,mysql_query已被弃用,您应该使用mysqli或PDO。
您可以使用-同样不推荐使用的- mysql_num_rows函数来计算行数。在您的情况下,0行不是有效代码。
发布于 2012-06-19 09:20:55
这
if($sql==FALSE)大概应该是这样的
if(mysql_num_rows($sql) == 0)编辑:我同意,mysqli或PDO现在是首选。
发布于 2012-06-19 11:16:32
问题可能出在这一行:
if($sql==FALSE)
{
apologize("Your download code is invalid. Please try again");
}因为sql是一个字符串,所以它接受的是true,并将其作为有效的传递。为了避免sql注入,您可能还想做的一件事是使用参数,而不是直接注入用户输入。
$sql = mysql_query("SELECT * FROM wd009 where uniqueCode='$uniqueCode'"); 相反,可以这样做:
$stmt = $mysqli->prepare("SELECT * FROM wd009 where uniqueCode=?");
$stmt->bind_param($uniqueCode);
$stmt->execute();
while ($stmt->fetch()) {
.....对于update语句,您也需要这样做。
如果表中有大量数据,则可能需要限制SQL语句中返回的列,以便减轻数据库的负载。
https://stackoverflow.com/questions/11093169
复制相似问题