mysql_affected_rows()解决方法?

时间:2012-01-12 15:45:49

标签: php mysql sql-update

我将此代码用作电子邮件确认脚本的一部分。它工作得很好,除了我无法找到一种方法来区分某人提供无效的电子邮件地址与他们只是刷新页面时(即已经确认他们的帐户)。我能想到的唯一想法是在users表中放置一个总是得到更新的时间戳字段,但我希望有更好的方法。我认为REPLACE可以解决问题,但是,虽然email是唯一的,但它不是主键。

if (isset ($email, $token, $correctToken)){    
    $success = FALSE; //Set the $success variable so that we don't get an error when testing for it later
    if ($token == $correctToken) {
        $confirm = mysql_query("UPDATE users
                        SET conf = 'TRUE'
                        WHERE email = '$email'");
        if (mysql_affected_rows() == 1) {
            echo "Thank you!  Your email address is confirmed and your account is actived.";
            $success = TRUE;
        }
    }
    if (!$success) {
        echo "There was a problem with the confirmation.  Try the link in your email again or contact us at Support@WiseRenters.com";
        // Send  email to admin to notify of error
        exit;
    }
}

提前感谢您的建议! 比利

编辑:$email$token变量是通过$ _GET或$ _POST提供的,如果不明显的话。

1 个答案:

答案 0 :(得分:1)

重定向会阻止他们刷新 - 但是如果他们再次单击电子邮件中的链接会怎么样?

您应该检查当前用户是否被激活。

$sql = "SELECT id, conf FROM users WHERE email = '{$email}'";
$exec = mysql_query($sql) or die(mysql_error());
list( $id, $conf ) = mysql_fetch_row($exec);

if( $conf ) {
    // Redirect them to their profile with a message saying "your account has already been activated"
    header("Location: /profile?already_activated");
    exit;
}

// your code
$confirm = mysql_query("UPDATE users
                    SET conf = 'TRUE'
                    WHERE id = '{$id}'");

回应你的评论:

请注意,这只会为尚未激活的用户添加其他查询。如果它们已激活,则会发生重定向,并且页面仍然只运行1个查询。

要稍微优化一下,您可以根据电子邮件地址选择用户ID和确认状态。然后,如果确实需要激活它们,您可以根据用户ID而不是电子邮件激活它们。由于整数键的速度要快得多,因此2个查询的组合时间与基于字符串列更新的1个查询大致相同。我更新了代码以反映这一点。

此外,可能不会经常访问此页面。从这里进行的任何优化都将是微观的,并没有那么有用。

顺便提一下,我希望您在电子邮件中使用mysql_real_escape_stringconf是布尔值true / false而不是字符串'true'/'false'。

相关问题