Wilest
Wilest

Reputation: 1860

mysql query in php evaluates to true wrongly

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";
}

Upvotes: 2

Views: 103

Answers (4)

jncraton
jncraton

Reputation: 9132

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";
}

Upvotes: 0

matino
matino

Reputation: 17705

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.

Upvotes: 1

Adrian Serafin
Adrian Serafin

Reputation: 7705

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

Upvotes: 5

Marco
Marco

Reputation: 57573

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.

Upvotes: 4

Related Questions