RE: [PHP] Update or add?

From: Date: Fri, 30 Jun 2006 21:00:00 +0000
Subject: RE: [PHP] Update or add?
Groups: php.general 
Request: Send a blank email to php-general+get-239029@lists.php.net to get a copy of this message
> > I have a table where I want to update each record with today's date > as it's hit, or add the record if it's not in there: > > +------+-----------------+------------+ > | id | creation_date | last_hit | > +------+-----------------+------------+ > > I'm trying to do this with a minimum of hits to the db, so rather > than first searching to see if a matching record is in there, I > thought I'd just go ahead and update the matching record, check to > see if it failed, and if it failed then add a new one, like this: > > $id = $_GET['id']; > // Update > $query = "update table set last_hit=NOW() where id='$id'"; > $result = mysql_query($query); > // Add > if(the update failed) { > $query = "insert into table (id,creation_date,last_hit) values > ('$id',NOW(),NOW())"; > $result = mysql_query($query); > } > > What's the fastest way to check if the update failed? > Maybe you should be looking at using REPLACE instead of INSERT or UPDATE. REPLACE will update the record if it exists, OR add it if it doesn't. JM

« previous php.general (#239029) next »