检查电子邮件是否存在但返回空查询?

时间:2014-07-29 14:45:05

标签: php mysql

我正在尝试编写一些代码,用于检查我的表中是否存在电子邮件但是仍然收到"查询为空"错误。我似乎无法找到查询返回空的原因?

我是PHP的新手,我正在网上关注这个教程,我所遵循的代码似乎完全相同。我的代码:

recover1.php

<?php require_once('Connections/localhost.php'); ?>
<?php
  session_start();
    if(isset($_SESSION['MM_Username'])) {
    header("Location: My_Account.php");
    die;
}
?>

<?php include('functions2.php'); ?>

<?php
$mode_allowed = array('username', 'password');
if (isset($_GET['mode']) === true && in_array($_GET['mode'], $mode_allowed) == true) {
    if (isset($_POST['email']) === true && empty($_POST['email']) === false) {
        if (email_exists(($_POST['email'])) === true) {
        echo "ok";
        } else {
            echo '<div id="error"> We could not find that email address, please try again. </div>';
        }
    }
?>  

<?php   
} else {
    header('Location: subscribe.php');
    exit();

}
?>

functions2.php

    <?php

function sanitize($data) {
    return mysql_real_escape_string($data); 
}

function recover ($mode, $email) {
    $email = sanitize($email);
    $mode = sanaitize($mode);
    $user_data = user_data(UserID_from_email($email), `Username`);
    if ($mode == 'username') {
        email($email, 'Your Username', "Hi/n As requested your username is " . $user_data['Username'] . "/n/n Infinity Crates");
    } else if ($mode == 'password') {
        //recover password
    }
}

function email_exists($email) {
    $email = sanitize($email);
    $query = mysql_query("SELECT COUNT (`UserID`) FROM `users` WHERE `Email` = '$email'");
    $result = mysql_query($query) or die(mysql_error());
    return (mysql_result($result, 0) == 1) ? true : false;
}

function UserID_from_email($email) {
    $email = sanitize($email);
    return mysql_result(mysql_query("SELECT `UserID` from `Users` WHERE `Email` = '$email'"), 0, `UserID`); 
}

function email($to, $subject, $body) {
    mail($to, $subject, $body, 'From: infinitycrate@gmail.com');    
}

?>

2 个答案:

答案 0 :(得分:2)

你正在使用mysql_query 2次。

成功:

function email_exists($email) {
    $email = sanitize($email);
    $query = "SELECT COUNT (`UserID`) FROM `users` WHERE `Email` = '$email'";
    $result = mysql_query($query) or die(mysql_error());
    return (mysql_result($result, 0) == 1) ? true : false;
}

您甚至可以像这样修改您的功能:

function email_exists($email) {
    $email = sanitize($email);
    $result = mysql_query("SELECT * FROM `users` WHERE `Email` = '$email'") or die(mysql_error());
    return (mysql_num_rows($result) > 0) ? true : false;
}

注意:PHP 5.5不推荐使用默认的Mysql API。请改用PDO和Mysqli。有关详细信息,请查看http://php.net/manual/en/mysqlinfo.api.choosing.php

答案 1 :(得分:0)

您的函数需要全局化mysql_connect资源变量或将资源传递给函数。检查您的第一个require_once文件,看看mysql_connect资源是否存储在变量中。如果没有,修改它以将资源保存到$dbh之类的变量,并通过在这些函数中插入global $dbh;作为第一行来修改“email_exists”,“sanitize”和“UserID_from_email”函数。 p>