"how to check if a row exists in mysql? (i.e. check if an email exists in mysql)" Code Answer

2

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).

edit: i made an previous error in my syntax where i used mysqli_query() twice. please consult the revision(s).

i.e.:

if (!mysqli_query($con,$query)) which should have simply read as if (!$query).

  • i apologize for overlooking that mistake.

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

}

and in your case:

$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

}

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;

            }
        }
    }

or a pdo method with a prepared statement:

<?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.";
    }


    }
?>
  • prepared statements are best to be used to help protect against an sql injection.

n.b.:

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.

  • fyi: forms default to a get method if not explicity instructed.

note: <input type = "text" name = "var"> - $_post['var'] match. $_post['var'] no match.

  • post arrays are case-sensitive.

consult:

  • http://php.net/manual/en/tutorial.forms.php

error checking references:

  • 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

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).

  • you must use the same one from connecting to querying.

consult the following about this:

  • can i mix mysql apis in php?

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: check if row exists

the mysql_* functions are deprecated and will be removed from future php releases.

  • it's time to step into the 21st century.

you can also add a unique constraint to (a) row(s).

references:

  • 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)
By bluecarbon on July 17 2022

Answers related to “how to check if a row exists in mysql? (i.e. check if an email exists in mysql)”

Only authorized users can answer the Search term. Please sign in first, or register a free account.