MySQL/PHP database value check not allowing for extra characters
I have a username check in PHP, and whenever someone enters the value 'username2' when 'username' already exists, it returns that it is already taken.
include 'connect.php';
$username = $_POST['r_username'];
$password = $_POST['r_password'];
$email = $_POST['r_email'];
$开发者_开发百科qry = "SELECT * FROM users WHERE 'username' = '$username'";
if(mysql_query($qry) != ''){
echo "<script type='text/javascript'>
alert('This username has already been taken!');
window.location = 'register.php';
</script>";
}else{...
Thanks for your help!
$qry = "SELECT * FROM users WHERE 'username' = '$username'";
I don't know much about php or MySql, but just wanted to ask if the field_name should be 'username' or without quotes. May be its taking it as value instead of column_name. I'm not sure
You are using mysql_query()
incorrectly. It returns a resource to be used in other functions.
Read the manual: http://php.net/manual/en/function.mysql-query.php
$query_response = mysql_query($qry)
if (mysql_num_rows($query_response) > 0) {
echo "<script type='text/javascript'>
alert('This username has already been taken!');
window.location = 'register.php';
</script>";
}
else {
echo 'This username has not been taken yet. Please, proceed';
}
Take a look what mysql_query returns. Your condition (mysql_query($qry) != ''
) will always be true
Also, use backticks instead of apostrophes (') to enclose column names in queries. Now you comparing whatever $username string is with string username
, but not a username
column.
BTW, I agree with the others. Your query is not protected against SQL Injections. Use mysql_real_escape_string like so:
"SELECT * FROM users WHERE `username` = '".mysql_real_escape_string($username)."'";
精彩评论