如何检查MySQL中是否存在行? (即检查MySQL中是否存在电子邮件) [英] How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

查看:114
本文介绍了如何检查MySQL中是否存在行? (即检查MySQL中是否存在电子邮件)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助检查数据库中是否存在行.就我而言,该行包含一个电子邮件地址.我得到结果:

I need help checking if a row exists in the database. In my case, that row contains an email address. I am getting the result:

email no longer exists publisher@example.com

这是我当前正在使用的代码:

This is the code I'm currently using:

if (count($_POST)) {
    $email = $dbl->real_escape_string(trim(strip_tags($_POST['email'])));

    $query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
    $result = mysqli_query($dbl, $query);
    if (is_resource($result) && mysqli_num_rows($result) == 1) {
        $row = mysqli_fetch_assoc($result);
        echo $email . " email exists " .  $row["email"] . "\n";
    } else {
        echo "email no longer exists" . $email . "\n";
    }
}

是否有更好的方法来检查MySQL中是否存在行(就我而言,检查MySQL中是否存在电子邮件)?

Is there a better way to check if a row exists in MySQL (in my case, check if an email exists in MySQL)?

推荐答案

以下经过尝试,测试和验证的方法来检查是否存在行.

The following are tried, tested and proven methods to check if a row exists.

(其中一些我自己使用过,或者曾经使用过).

(Some of which I use myself, or have used in the past).

编辑:我在语法上犯了一个先前的错误,我两次使用mysqli_query().请查阅修订版本.

I made an previous error in my syntax where I used mysqli_query() twice. Please consult the revision(s).

即:

if (!mysqli_query($con,$query)),应该简单地读为if (!$query).

  • 我很抱歉忽略了这个错误.

旁注: '".$var."''$var'都做相同的事情.您可以使用任何一种,两者都是有效的语法.

Side note: Both '".$var."' and '$var' do the same thing. You can use either one, both are valid syntax.

这是两个已编辑的查询:

Here are the two edited queries:

$query = mysqli_query($con, "SELECT * FROM emails WHERE email='".$email."'");

    if (!$query)
    {
        die('Error: ' . mysqli_error($con));
    }

if(mysqli_num_rows($query) > 0){

    echo "email already exists";

}else{

    // do something

}

以及您的情况:

$query = mysqli_query($dbl, "SELECT * FROM `tblUser` WHERE email='".$email."'");

    if (!$query)
    {
        die('Error: ' . mysqli_error($dbl));
    }

if(mysqli_num_rows($query) > 0){

    echo "email already exists";

}else{

    // do something

}

您还可以将 mysqli_与预准备的语句一起使用方法:

You can also use mysqli_ with a prepared statement method:

$query = "SELECT `email` FROM `tblUser` WHERE email=?";

if ($stmt = $dbl->prepare($query)){

        $stmt->bind_param("s", $email);

        if($stmt->execute()){
            $stmt->store_result();

            $email_check= "";         
            $stmt->bind_result($email_check);
            $stmt->fetch();

            if ($stmt->num_rows == 1){

            echo "That Email already exists.";
            exit;

            }
        }
    }

或带有准备好的语句的PDO方法 :

<?php
$email = $_POST['email'];

$mysql_hostname = 'xxx';
$mysql_username = 'xxx';
$mysql_password = 'xxx';
$mysql_dbname = 'xxx';

try {
$conn= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); 
     $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
     exit( $e->getMessage() );
}

// assuming a named submit button
if(isset($_POST['submit']))
    {

        try {
            $stmt = $conn->prepare('SELECT `email` FROM `tblUser` WHERE email = ?');
            $stmt->bindParam(1, $_POST['email']); 
            $stmt->execute();
            while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            }
        }
        catch(PDOException $e) {
            echo 'ERROR: ' . $e->getMessage();
        }

    if($stmt->rowCount() > 0){
        echo "The record exists!";
    } else {
        echo "The record is non-existant.";
    }


    }
?>

  • 最好使用准备好的语句来防止SQL注入.
  • N.B.:

    在处理上面使用/概述的表单和POST数组时,请确保POST数组包含值,表单使用POST方法并为输入匹配命名属性.

    When dealing with forms and POST arrays as used/outlined above, make sure that the POST arrays contain values, that a POST method is used for the form and matching named attributes for the inputs.

    • 仅供参考:如果未明确指示,则表单默认为GET方法.

    注意:<input type = "text" name = "var">-$_POST['var']匹配. $_POST['Var']没有匹配项.

    Note: <input type = "text" name = "var"> - $_POST['var'] match. $_POST['Var'] no match.

    • POST数组区分大小写.

    咨询:

    检查引用时出错:

    • http://php.net/manual/en/function.error-reporting.php
    • http://php.net/manual/en/mysqli.error.php
    • http://php.net/manual/en/pdo.error-handling.php

    请注意,如果您正在访问此问答,并且您正在使用mysql_进行连接(并进行查询),则MySQL API不会混在一起.

    Please note that MySQL APIs do not intermix, in case you may be visiting this Q&A and you're using mysql_ to connect with (and querying with).

    • 从连接到查询,您必须使用相同的密码.

    请咨询以下内容:

    如果您使用的是mysql_ API,但别无选择,请查阅以下有关堆栈的Q& A:

    If you are using the mysql_ API and have no choice to work with it, then consult the following Q&A on Stack:

    不推荐使用mysql_*函数,这些函数将从将来的PHP版本中删除.

    The mysql_* functions are deprecated and will be removed from future PHP releases.

    • 该是进入21世纪的时候了.

    您还可以向(a)行添加UNIQUE约束.

    参考文献:

    • http://dev.mysql.com/doc/refman/5.7/en/constraint-primary-key.html
    • http://dev.mysql.com/doc/refman/5.7/en/alter-table.html
    • How to check if a value already exists to avoid duplicates?
    • How add unique key to existing table (with non uniques rows)

    这篇关于如何检查MySQL中是否存在行? (即检查MySQL中是否存在电子邮件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆