Bill
Bill

Reputation: 141

MySQL Update problem

$result=mysql_query(" UPDATE xxxxxx_users SET User_Password='$Password' WHERE FstName='$First' AND LstName='$Last'",$db)  or die ("Password update successful!");
echo "Update failed, unknown user";

This correctly updates the db when the first and last names match and the db is not affected when they don't. My only issue is I always display the Update failed, unknown user message. what did I do wrong? Thanks.

Upvotes: 3

Views: 126

Answers (3)

leepowers
leepowers

Reputation: 38298

The mysql_query function returns true when an SQL query is successful:

For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.

Your code is assuming that the query returns the number of rows effected. Use the mysql_affected_rows function for this purpose:

$result=mysql_query(" UPDATE xxxxxx_users SET User_Password='$Password' WHERE FstName='$First' AND LstName='$Last'",$db)
if (mysql_affected_rows() > 0)
  die ("Password update successful!");
else
  echo "Update failed, unknown user";

Upvotes: 5

user276167
user276167

Reputation: 29

You probably need to do this the other way round...

$result=mysql_query(" UPDATE xxxxxx_users SET User_Password='$Password' WHERE FstName='$First' AND LstName='$Last'",$db)
     or die ("Update failed, unknown user"); 

echo "Password update successful!";

Upvotes: 2

glebm
glebm

Reputation: 21090

If the first part (mysql_query) evaluates to true, there is no need to evaluate the second or part (die). You can use and instead.

And, please, read about SQL Injections.

A suggestion to your coding style:

Something like this:

if ($result)
   ...success
else 
   ...fail

is much more readable.

Upvotes: 0

Related Questions