I’m getting errors with the PHP login script I am using on my site.
I wanted to add code which checks if the user is banned when he/she logs in.
But for some reason(s), it’s not working properly; it always outputs “You are banned,” even if the ban field/attribute contains on “n” for false in the MySQL “users” table.
I’ve tried fixing the code, but I still get errors. This is my code:
$bancheck = mysql_query("SELECT * FROM users WHERE ban = '".$_POST['username']."'" ) or die(mysql_error());
$ban = mysql_fetch_array($bancheck);
if ($ban = 'y') {
die('You are banned...');
}
The MySQL field which I’ve to check against is called “ban” and value is either “y” for “true,” or “n” for “false.”
1: Should be a comparison, not an assignment.
This line is incorrect:
It should be:
I’m assuming there’s an extra brace there by accident also.
2: SQL injection
You should not pass your string straight
from $_POSTinto your MySql as you are vulnerable to SQL injection. You should escape it like so:3: Ban != user
You should not compare
banto the username passed in via the form anyway, as ban will either hold the string ‘y’ or ‘n’. You should compare the username (passed in) to the approriate username field in your database table. Like so:4: Proper iteration & comparison
Instead of the
mysql_fetch_array()function I’d use themysql_fetch_assoc()function because it returns an associative array.This will return an associative array for each row returned (contained in the MySql resource
$bancheck) so you need to iterative through them (even though it should only return one array) like so:But I’d add in some more code just to help with any other problems: