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.
SELECT EXISTS(
SELECT 1
FROM plus_signup
WHERE userid = 'alex'
) AS user_exists;
user_exists
1
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.';
}
?>
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.
<?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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| 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! | |