简体   繁体   中英

Login script - counting rows or using COUNT('column')

I've been dabbling abit with a login script (PHP and MySQL), using various online tutorials. Today I became curious as to which way is the best to check if a username and password is valid. Every tutorial I've read so far checks the number of row returned, like this:

SELECT stuff FROM users WHERE username = input_username AND password = input_password
count the rows returned
if rows equal to one
login
else
display error message

I was just thinking if it's equally viable to use COUNT and check that value instead, like this:

SELECT COUNT(stuff) FROM users WHERE username = input_username AND password = input_password
if returned value equal to one
login
else
display error message

I've tried both and both work return the intended result. So is there any reason to choose one over the other?

They are both valid approaches. You would use the former when you needed additional info about the user, eg, their UserID.

You should definitely go with second SQL-statement if you don't need any of the information stored. COUNT() is better for performance. Although the reason people tend to stick to the first one is because they will be needing information about the user if rows returned is positive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM