Hi guys! I just need to know how to use a php if statement to check if two values are in a mysql database. I need this so that I can check a user's username and password and see if it exists. I only need a simple answer, I'm not a php genius! Thanks in advance, - Tony
Well if you are thinking of finding out which username is in registered already in database you can use something like this: $username = $_POST['username']; // All your forms should go here. $query = "SELECT username FROM users WHERE username ='$username'"; $query_run = mysql_query($query); if (mysql_num_rows($query_run)==1) { echo 'The Username '.$username.' Already Exists.'; }else { echo ' The username '.$username.' Does not Exist.'; } Good luck.
Vulnerable to SQL Injection attack. Whenever using variables directly in SQL statements that are defined by the visitor ALWAYS "escape" dangerous characters. In fact, you should use PDO or mysqli with placeholders to be secure. Although an example..the above code would allow any visitor to have the ability to execute SQL statements.
Another glitch. "SELECT username FROM users WHERE username = '$username' and password = '$password';" Code (markup): after protecting against injection, then check that you only had one or zero rows returned. Zero means bad username or password (or the user isn't registered), one means a good login, more than one means a hack attack!
I think I understand (sorry, I'm a n00b). But wouldn't that mean that this is secure already? After all, the code only works if there is only one row $username = mysql_real_escape_string($_POST['username']); $password = mysql_real_escape_string($_POST['password']); $sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'"; $query = mysql_query($sql, $con); if (mysql_num_rows($query)==1) { echo 'Account detected. Logging in...'; //login } else { echo 'Account not detected'; } PHP:
If there's one row with the username, your original code works. Post #8 is better, since you're checking both username and password. I'd use a different message if the count was 0 - something like "incorrect login or password". No reason to give a hacker more information than you have to.