2

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); 
2
  • 2
    If you mean 'does it work?'....it does... (if the returned value is >1 then rows with name='John' exist, and if it's 0 then they don't) Commented Jan 9, 2012 at 7:06
  • 1
    What @mathematical.coffee says is correct but using LIMIT might be faster. A SELECT COUNT(*) is a complete table or index scan while using SELECT name FROM table WHERE name = 'John' LIMIT 1 would stop when the first match is found. Commented Jan 9, 2012 at 7:12

4 Answers 4

2

you could use straight forward ,

mysql_num_rows() ; 

eg :

$con = mysql_connect($host,$uname,$passwd) mysql_select_db($dbase,$con); $result = mysql_query($query,$con);// query : SELECT * FROM table WHERE name='jhon'; if( ! mysql_num_rows($result)) { echo " Sorry no such value "; } 
Sign up to request clarification or add additional context in comments.

Comments

1

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%' 

Comments

1

I'd say yes.

$result = mysql_query("SELECT COUNT(*) AS 'nb' FROM table WHERE name = 'John'"); $line = mysql_fetch_array($result, MYSQL_ASSOC); $count = $line['nb']; 

Will give you the number of matching rows.

Comments

1
$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"; } 

1 Comment

but using the code which is suggested above by @Vijeenrosh P.W is appreciated

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.