Check if a MySQL row exists using PHP’s PDO object.

In this tutorial, I will be showing you how to check if a row exists in MySQL. To do this, I will be using PHP’s popular PDO object.

First of all, let’s assume that we have a users table and that we want to check if a given email address already exists in our database.

Take a look at the following example:

//Connect to MySQL using the PDO object.
$pdo = new PDO(
    "mysql:host=localhost;dbname=test",
    'root',
    'mypassword'
);

//The email we are looking for.
$emailToLookFor = '[email protected]';

//The SQL query.
$sql = "SELECT COUNT(*) AS num FROM `users` WHERE email = :email";

//Prepare the SQL statement.
$stmt = $pdo->prepare($sql);

//Bind our email value to the :email parameter.
$stmt->bindValue(':email', $emailToLookFor);

//Execute the statement.
$stmt->execute();

//Fetch the row / result.
$row = $stmt->fetch(PDO::FETCH_ASSOC);

//If num is bigger than 0, the email already exists.
if($row['num'] > 0){
    echo 'Row exists!';
} else{
    echo 'Row does not exist!';
}

In the PHP example above, we:

  1. Connected to our MySQL database using PDO.
  2. Created an SELECT SQL query that uses MySQL’s COUNT function. This COUNT function will return the number of rows that match a certain WHERE condition. In this case, our WHERE condition is querying a column called email.
  3. Prepared our SQL statement using the PDO::prepare function.
  4. Binded the email address to the “:email” parameter in our SQL statement.
  5. Executed the statement.
  6. Returned the results of the statement using the PDOStatement::fetch function. I used the PDO::FETCH_ASSOC option because I wanted an associative array.

Finally, we checked to see if num in our $row array is bigger than zero. If it is bigger than zero, then it means that a row with that email address already exists.

Facebook Comments