How to Check if a Record Exists in SQL Database Table with PHP

Hello,

Have you been in a situation where you need to check if either a phone number or a user, for example, exists in your database? When I didn’t know how to do that, I looked through several articles looking for the best and most efficient way of doing it until I found this one.

1. Let’s say we have a table called ‘users’ and it has two columns: id, name. This is our table:

|  id |   name  |
-----------------
|  1  |  Lewis  | 
|  2  |  Martin |
|  3  |  Paul   |
|  4  |  Bryan  |

We want to check if user with id 3 exists.

$q="SELECT COUNT(1) FROM users WHERE id=3";
$r=mysql_query($q);
$row=mysql_fetch_row($r);
//Now to check, we use an if() statement
if($row[0] >= 1) {
 print "Record exists";
  } else {
 print "Record doesn't exist";
}

The script would output “Record exists”, but what if we want to check if user with id = 5 exists? We would simply change the query ($q) to id=5:

$q="SELECT COUNT(1) FROM users WHERE id=5";

The script would not output “Record doesn’t exist”.

Explanation

$q : Has the query we are going to execute. SELECT COUNT(1) will count records.

$r : Executes the query

$row : Fetches the data SELECT COUNT(1) obtained

if($row[0] >= 1)  : Will check that if the count is greater or equal than 1, means that the record exists, otherwise, it doesn’t.

Any question, please do not hesitate to contact me! If you want me to write about a specific topic, please leave a comment below and I’ll do my best to have it written for you.

Best Regards,

Richi

Owner of Juapo2Services

Looking for quality web hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , , , , , , , , | Posted under Programming/Coding | RSS 2.0

Author Spotlight

Richi González

Richi González

I started programming when I was 12. I'm a Developer and have been working with the Clip-Bucket script since it came out. I became a Liaison between Arvixe and Clip-Bucket, so I am here to assist you with anything you need regarding Clip-Bucket or any particular computer-related subject you need. Best Regards, Richi

Leave a Reply

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


8 × 3 =

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>