2

somewhere I'm doing something wrong, my query results to true instead of false. In my table the id 246 does exist but the lev is zero in the table. What am I doing wrong, this query should result to false. It echo's success but it does not update the table.

if (mysql_query("UPDATE ex_usrs SET lev = '1' WHERE id = '246' AND lev = '3'")) {
echo "success";
} else {
echo "fail";
}

4 Answers 4

5

It returns true because query was successfull and it affects 0 rows. If you want to check if something actually gets updated use

mysql_affected_rows 

link to documentation

Sign up to request clarification or add additional context in comments.

Comments

4

You're not doing anything wrong: mysql_query statement returns true because it is executed correctly!
This does not mean that any row gets updated in your database.

1 Comment

Ok thank you I understand now. I was under the impression it returns true when the records were updated.
1

From docs:

For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.

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

The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.

Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.

Don't use mysql_query to check if you really did update some rows. Use mysql_affected_rows() instead.

Comments

0

From your description, it sounds like the query is running, but not making any changes. As others have noted, this is the expected behavior.

You also said that lev is zero for the record with id 246. This explains why the update is failing. You are only updating the record with id 246 if lev is already set to 3. Depending on your situation, either of the following may work better for you:

if (mysql_query("UPDATE ex_usrs SET lev = '1' WHERE id = '246' AND lev = '0'")) {
    echo "success";
} else {
    echo "fail";
}

or just ignore the current state lev completely:

if (mysql_query("UPDATE ex_usrs SET lev = '1' WHERE id = '246'")) {
    echo "success";
} else {
    echo "fail";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.