0

Possible Duplicate:
php - check record exists db - error show

I am currently trying to add a user to the database. I want to to check if the user exists, and IF SO, then just update a few fields. If IT DOESNT, then it should completely insert a new record.

$result22 = mysql_query("SELECT COUNT(1) FROM newsite WHERE user = '$username'");

if($result22){
$SQL = "UPDATE newsite SET active = '1' WHERE user = '$username'";
$_SESSION['username'] = $_GET['user'];
$result = mysql_query($SQL);
echo("lol."); // TEST
header("Location: ./share.php?user=$username");

}
if(!$result22){

$SQL = "INSERT INTO newsite (user, active) VALUES ('".$username."', '1')";
$_SESSION['username'] = $_GET['user'];
$result = mysql_query($SQL);
echo("NOPE."); //TEST
header("Location: ./share.php?user=$username");
}
}

I'm not really sure why, but no matter what it ALWAYS outputs "lol." (aka, the user exists.) it completely ignores the other if.

Community
  • 1
  • 1
user1508174
  • 49
  • 1
  • 7
  • You have an extra closing brace. Not to mention you should combine it to just if ($result22) { ... } else { ... } – Raekye Jan 12 '13 at 09:53

2 Answers2

2
$result22 = mysql_query("SELECT COUNT(1) FROM newsite WHERE user = '$username'");

if($result22){

Unless you have error in your SQL code, mysql_query returns resultset that is always resolved to true

Also:

Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Zoe
  • 27,060
  • 21
  • 118
  • 148
dev-null-dweller
  • 29,274
  • 3
  • 65
  • 85
0

You can also use the mysql_num_rows function, which returns the number of row of the last result set

if(mysql_num_rows()>0)
{

}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Bhavik
  • 9
  • 1
  • 7