1

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!

Christopher
  • 277
  • 5
  • 19
  • 1
    Odd, it shouldn't do that. Can you show what `$qry` contains in such a case? Also, your code is vulnerable to [SQL injection.](http://stackoverflow.com/questions/601300/what-is-sql-injection) – Pekka May 05 '11 at 06:24
  • 1
    how long is username column in database? – Marco May 05 '11 at 06:25
  • 1
    Hello, [little bobby tables](http://bobby-tables.com/) – Quentin May 05 '11 at 06:26
  • I know it's vulnerable, I have mysql_real_escape_string and addslashes for that. @ Dorward, seen the strip before but I love it still. – Christopher May 05 '11 at 06:42

3 Answers3

2

$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

Mayank
  • 5,454
  • 9
  • 37
  • 60
1
$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)."'";
Nemoden
  • 8,816
  • 6
  • 41
  • 65
  • I entered a username with a number on the end and it worked great, but when I entered the exact same username (After verification that it was in the database), it didn't throw an error. – Christopher May 05 '11 at 06:32
1

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

Galen
  • 29,976
  • 9
  • 71
  • 89
  • I've used it for tons of other fetches like the one above, and it works fine. What other method should I be using then? – Christopher May 05 '11 at 06:50