What's the best way to check whether the value is in the database?
Am I doing it correct?
$result = mysql_query("SELECT COUNT(*) FROM table WHERE name = 'John'"); $count = count($result); Yes you are doing it right, if you are only concerned with checking if there are any records where name='john'
SELECT COUNT(*) FROM table WHERE name = 'John' will return the no. of records where name field is 'John'. if there are no records then it will return 0, and if there are any records it will return the number of records.
But the above query will miss the entries where name is 'John Abraham' or 'V john', to include even these
you can modify your query like this.
SELECT COUNT(*) FROM table WHERE name like '%John%' $result = mysql_query("SELECT COUNT(*) as user FROM table WHERE name = 'John'"); $line = mysql_fetch_array($result, MYSQL_ASSOC); $count = $line['user']; if($count!=0) { echo "user exists"; } else { echo "There is no such user"; }
name='John'exist, and if it's 0 then they don't)LIMITmight be faster. ASELECT COUNT(*)is a complete table or index scan while usingSELECT name FROM table WHERE name = 'John' LIMIT 1would stop when the first match is found.