tags:

views:

45

answers:

4

Kind of an unclear question but I'm trying to check if a username has been taken or not. The code I have now isn't erroring but it's also not working, when echoing the $username variable I get nothing.

$sql="SELECT people_username FROM people WHERE people_username='{$_POST['username']}'";

    //Set the result of the query as $username and if the select fails echo an error message
    if ($username = !mysql_query($sql,$con)) {
        die('Error: ' . mysql_error());
    }

    else if ($_POST['username'] == $username){
        $errors[  ] = 'This username is already in use, please try again...sorry';
    }

Is it a syntax error or is my logic wrong?

+2  A: 

i would just do

$resource = mysql_query("SELECT people_username FROM people WHERE people_username='".mysql_escape_string($_POST['username'])."'");
if(!$resource) {
    die('Error: ' . mysql_error());
} else if(mysql_num_rows($resource) > 0) {
    $errors[  ] = 'This username is already in use, please try again...sorry';
} else {
    //username is not in use... do whatever else you need to do.
}
seventeen
Thanks, this is what I was looking for!
Charlie
don't copy and paste that I didn't include mysql_real_escape_string, well I just did.
seventeen
Yea I already sanitized it, thanks.
Charlie
A: 

Your code is wrong.

It should be something like this:

$sql="SELECT people_username FROM people WHERE people_username='".mysql_escape_string($_POST['username'])."'";

//If the select fails echo an error message
if (!($result = mysql_query($sql,$con))) {
    die('Error: ' . mysql_error());
}

$data = mysql_fetch_assoc($result);

if ($data == null){
    $errors[  ] = 'This username is already in use, please try again...sorry';
}

Notice that for security reasons you need to escape the strings you use in SQL queries.

Johnco
+1  A: 

If some cheeky user happens to try: '; DROP people; -- as a username, you'd be in big trouble.

You may want to check the following Stack Overflow post for further reading on this topic:

As for the other problem, the other answers already addressed valid solutions. However, make sure to fix the SQL injection vulnerability first. It is never too early for this.

Daniel Vassallo
i think you cant do that anymore. you can extend the select but im prety sure mysql_query just executes 1 query.
useless
A: 
  1. mysql_query($sql,$con) returns a resultset (which may be empty)
  2. you are not testing any condition with if($var = !'value'), you are just assigning a negated resultset to the variable $username (what beast that is, I am not sure)

My suggestion: Simplify the code, do not overload lines of code with multiple tasks. 3. List item

Majid
With ifs we frequently forget to use `==`: so this is wrong `if($a = 3)` because it is an assignment which changes the value of `$a` to `3` and is always true. To check if `$a` is equal to `3` we need `if($a == 3)`
Majid