Check Whether a Record Exists in MySQL

Checking whether a record exists in a MySQL table

When you only need to know whether a matching row exists, do not fetch an entire record set. In SQL, EXISTS expresses this directly; in application code, a SELECT 1 ... LIMIT 1 query is also efficient and simple.

SQL EXISTS

SELECT EXISTS(
    SELECT 1
    FROM plus_signup
    WHERE userid = 'alex'
) AS user_exists;
user_exists
1

PHP PDO prepared statement

This pattern is suitable for a signup check because the visitor-supplied user ID is bound as a parameter.

<?php
require 'config.php';

$userid = 'alex';
$query = 'SELECT EXISTS(SELECT 1 FROM plus_signup WHERE userid = :userid)';
$stmt = $dbo->prepare($query);
$stmt->execute([':userid' => $userid]);

$exists = (bool) $stmt->fetchColumn();
if ($exists) {
    echo 'User name already exists.';
}
?>

Count matching rows when you need the count

SELECT COUNT(*) AS matches
FROM plus_signup
WHERE userid = 'alex';

Use COUNT() when the actual number of matching rows matters. For a yes/no check, EXISTS avoids doing unnecessary work.

MySQLi prepared statement

<?php
$query = 'SELECT 1 FROM plus_signup WHERE userid = ? LIMIT 1';
$stmt = $connection->prepare($query);
$stmt->bind_param('s', $userid);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    echo 'User name already exists.';
}
?>

Related PHP topics: signup form, PDO, MySQLi, and if/else.




Subscribe to our YouTube Channel here



plus2net.com
Omar

19-02-2010

Thank you, That helped Me ..
Vinayak

06-03-2010

Thanks, the code solved the bug in my program.
Danoj

23-03-2010

Thank you very much for the code, its very important code to all programmers.
Elise

02-06-2010

Wauw!! I was searching for this code for hours!! Thank you so much!!
laan

08-07-2010

you rule that was exactly what i was looking for 3 second google search and blam on with the programming
Sashko

13-07-2010

Awesome! Concise and accurate.
Jan

09-12-2010

Thanks, I used to use the mysql COUNT function for this but this is much handier !
Satish Verma

03-02-2012

Thanks dear wow very nice code very useful this code
Cool

14-06-2012

Very very usefull script ... Thank you ...
Doug

26-06-2012

TOTALLY USEFUL. Exactly what was needed.
Scott

21-08-2012

Much more efficient than the count steps I was attempting. Thanks for the post.
Alex

15-11-2012

YES YES YES. After hours of struggling I have found the missing key mysql_num_rows($query) THANKS THANKS THANKS
Amanda

25-01-2013

Ha! Thank you, had the same problem as Alex.
sidharam anache

24-02-2013

very excellent answer.
Shane

02-10-2014

Spent HOURS trying to find this, finally got my problem solved!

Can't thank you enough for posting this!




SQL Video Tutorials










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer