Home » Php » php – mysql speed mysql_num_rows vs query limit 1

php – mysql speed mysql_num_rows vs query limit 1

Posted by: admin July 12, 2020 Leave a comment

Questions:

i had to check if a value (string) is in my database.

at the moment i do a

select a.email,b.vuid from user a, verteiler_user b where a.email=\''.$email.'\' and a.kid=' . $kid.' and b.vid=' . $vid . ' and a.uid = b.uid

as query with a mysql_num_rows, then check if >=1

But is it faster to do a query with limit 1; ? and check if a row is coming back ?

How to&Answers:

Yes. It would be faster to run a limit 1 query. And if all you’re doing is checking for the existence of a row, why bother returning all those columns? Simply select 1. That will be (negligibly) faster. BTW: Your code looks vulnerable to SQL injection attacks. Consider sanitizing the dynamic parts of your query with mysql_real_escape_string() or a similar function.

Answer:

LIMIT 1 will have better performance because it will stop matching when the LIMIT has been satisfied.

If you only ever expect 1 row, add LIMIT 1 to your query.

Also, if you are only checking for the presence of that string in the query, there is no need to use column names with SELECT in the query. Just use SELECT 1....

Answer:

you could try:

select count(*) from user a, verteiler_user b 
     where a.email=\''.$email.'\' and a.kid=' . $kid.' and b.vid=' . $vid . ' and a.uid = b.uid

and get the count by:

$row=mysql_fetch_array(...);
if ($row[0] > 0)  // is there a hit?
   ...