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:

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