2012-06-19 76 views
1

我目前正致力于构建一个下载平台,其中用户收到一个随机代码并使用它来访问一个MP3下载多达三个下载。我使用Python生成了一个随机代码列表,并将它们导入到一个SQL表中,其中一个空列用于关联的电子邮件地址和一个默认为0的使用次数。我编写了下面的PHP脚本,以便将电子邮件与特定的代码相关联并添加到计数中,以便下载最多可以访问三次。PHP MySQL SELECT查询只返回资源

$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都会返回一个资源。我已经检查了数据库连接,但是由于在下载代码正确的情况下正确更新了表,这似乎不成问题。

我试过调试这种方式,我可以想到的每一个方式,我真的很迷惑。任何帮助你可以提供将不胜感激!

+0

我想说如果你使用PDO,你会感觉更熟悉。它不再使用这些资源thingies。 – hakre

回答

1

正如您在手册中看到的,mysql_query总是返回有效查询的资源,因此您需要更改逻辑并计算返回的行数,而不是mysql_query的结果。

除此之外,mysql_query已弃用,您应该使用mysqli或PDO。

您可以使用 - 同样不推荐的功能 - 行数来计算行数。 0行在你的情况下将不是有效的代码。

+0

+1表示PDO。退出使用mysql_ *人! –

0

if($sql==FALSE) 

也许应该像

if(mysql_num_rows($sql) == 0) 

编辑:我同意,库MySQLi或PDO现在是首选。

0

可能的问题是这一行:

if($sql==FALSE) 
{ 
    apologize("Your download code is invalid. Please try again"); 
} 

因为SQL是它接受一个字符串是真实和把它当作有效。你也可能想避免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()) { 
    ..... 

你也想这样做,这样的更新语句了。

如果该表中有大量数据,则可能需要限制SQL语句中返回的列,以减少数据库上的负载。