Cover
Cover

Reputation: 77

How to UPDATE a certain row OR RETURN FALSE if it doesn't exist?

How to do it in one query?

Upvotes: 3

Views: 167

Answers (3)

RobertPitt
RobertPitt

Reputation: 57268

This is done for you already.

if(mysql_query('UPDATE table SET key = value WHERE id = 33')){/*....*/}

Using the where clause will check if the id exists and if it does then it will update it, what's the issue?

Upvotes: 1

Kel
Kel

Reputation: 7790

You may use mysql_affected_rows() function to check, whether any rows were affected by update. See for details: http://php.net/manual/en/function.mysql-affected-rows.php

Upvotes: 1

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181430

You can do something like:

function updateValue()
{
     mysql_query($sql); // your update goes here
     return mysql_affected_rows() > 0;
}

From BoltClock's comment:

Bear in mind that mysql_affected_rows() returns 0 if a row exists but the old and new values are equal (meaning there was no need for an update).

Upvotes: 4

Related Questions