How to check if a row exists in MySQL and PHP?

Spread the love

Sometimes, we want to check if a row exists in MySQL and PHP.

In this article, we’ll look at how to check if a row exists in MySQL and PHP.

How to check if a row exists in MySQL and PHP?

To check if a row exists in MySQL and PHP, we can run a prepared statement.

For instance, we write

$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;

        }
    }
}

to run the select $query.

We call $dbl->prepare to create the prepared statement from the $query string.

And we call bind_param to replace the placeholder with the $email value.

We call $stmt->execute() to run the prepared statement.

Next, we use $stmt->num_rows to check if a row is returned.

Conclusion

To check if a row exists in MySQL and PHP, we can run a prepared statement.

Leave a Reply

Your email address will not be published. Required fields are marked *