【问题标题】:Issue with correctly identifying if an email already exists in the database - PHP正确识别数据库中是否已存在电子邮件的问题 - PHP
【发布时间】:2012-02-24 19:11:12
【问题描述】:

是否有人知道如何更正此代码,以便它识别数据库中是否已存在电子邮件并显示错误。即使电子邮件在数据库中不存在,它当前也会显示错误消息——因此表单没有被提交:

$email = $_POST['email'];
//prepare and set the query and then execute it
$stmt = $conn2->prepare("SELECT COUNT(email) FROM users WHERE email = ?");
$stmt->bind_param('s', $email);
$stmt->execute();

// grab the result
$stmt->store_result();

// get the count
$numRows = $stmt->num_rows();

if( $numRows )
{
$errors = true;
 echo "<p class='red'>Email is already registered with us</p>";
}
else


//if we have no errors, do the SQL

【问题讨论】:

标签: php sql prepared-statement


【解决方案1】:

喜欢这个朋友:

$stmt = $mysqli->prepare("SELECT COUNT(email) FROM users WHERE email = ?");
$stmt->bind_param('s',$email);
$stmt->execute();
$stmt->bind_result($count);
while($stmt->fetch()){}

if(!empty($count)){ echo "Already Registered"; }

使用:

// grab the result
$stmt->store_result();

仅在您之前打开另一个连接时使用。

使用:

// get the count
$numRows = $stmt->num_rows();

当你只是计算 id 时,这是一种愚蠢的方法。

【讨论】:

    【解决方案2】:

    $numRows = $stmt-&gt;num_rows(); 将始终返回 1,因为您只选择一行(即使 COUNT(email) 的值为 0)

    $row = $stmt->fetch()
    echo $row[0]; // result of COUNT(email)
    

    【讨论】:

      【解决方案3】:

      select count(*) 将始终返回 1 行...

      您需要使用 SELECT * 或修改代码以从 SQL 语句中查询返回的结果

      【讨论】:

        猜你喜欢
        • 2020-03-17
        • 2019-09-17
        • 2013-06-08
        • 1970-01-01
        • 2014-03-15
        • 2014-05-10
        • 2021-04-24
        • 1970-01-01
        相关资源
        最近更新 更多