TAGS :Viewed: 11 - Published at: a few seconds ago

[ PHP If / else user exists on database set variable to 0 or 1 ]

I have this code to check if user exists in database. I want to assign $account to 1 if it exits, and 0 if it doesn't. I thought this code would work but its constantly setting $account to 0 so I think im missing a trick. Any help would be appreciated.

$con = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");

 if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }

mysql_select_db(DB_NAME, $con);

$sql="SELECT user_name FROM users";

$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if ($row['user_name'] == '$user_name'){
$account = 1;
}else{
        $account = 0;}

Thanks

Answer 1


You can't put variables in a string if you use single quotes ' (plus it's not necessary!). Below rectifies that issue, and shortens your if/else statement into a one-liner.

$account = $row['user_name']==$user_name ? 1 : 0;

Answer 2


I think this could be done a better way:

$con = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");

 if (!$con)
 {
 die('Could not connect: ' . mysql_error());
 }

mysql_select_db(DB_NAME, $con);

$account = (int)mysql_query("SELECT COUNT(*) FROM Users WHERE user_name='$user_name'");

That should store the correct value in account, i.e. 1 if the user is found and 0 if not.

Answer 3


You're query is returning multiple rows, and you are doing the comparison with the first row. you need to do something like the follwing to specify a single user (see sql statement change):

$sql="SELECT user_name FROM users WHERE user_name='".$user_name."' ";

$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
if ($row['user_name'] == '$user_name'){
$account = 1;
}else{
        $account = 0;}

also, to iterate over rows, you can see this example from http://php.net/manual/en/function.mysql-fetch-assoc.php:

while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

Answer 4


Change:

if ($row['user_name'] == '$user_name'){

to:

if ($row['user_name'] == $user_name){

Single quotes signifies a string. So, by putting your variable between the single quotes, you're trying to match $row['user_name'] to $user_name (not string inside the $user_name variable - but STRING "$user_name").

Double quotes also signifies a string, but you can put your variable between double quotes and $row['user_name'] will match to $user_name (a string inside the variable).

So, the following two examples are correct, and yours isn't:

if ($row['user_name'] == $user_name){
if ($row['user_name'] == "$user_name"){