Forum Moderators: open

Message Too Old, No Replies

UPDATE / INSERT auto detect

         

techtheatre

4:03 am on Jan 19, 2009 (gmt 0)

10+ Year Member



I frequently find that i write PHP scripts that generate either an UPDATE query or an INSERT query, depending if the data already exists, and then runs the query. A sample is below so you know what i mean. Is there some "magic" way to use one query that MySQL will treat as an UPDATE if the data is there, and if not, will create (INSERT) a new record? This functionality seems obvious, but I cannot find any documentation of it existing. Seems like a logical feature.

<?php
if($RecordExists=1){
$query = "UPDATE table_name SET Name='Bob', Age='27', Color='Blue' WHERE RecordId='123'";
}else{
$query = "INSERT INTO table_name (Name, Age, Color) VALUES ('Bob','27','Blue')";
}
mysql_query($query, $db);
?>

StoutFiles

6:47 am on Jan 19, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You'd have to make a query to see if the data is there or not, only then could you set $RecordExists to equal 1.

Habtom

6:56 am on Jan 19, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Check for "INSERT ... ON DUPLICATE KEY UPDATE"

techtheatre

8:06 am on Jan 19, 2009 (gmt 0)

10+ Year Member



STOUTFILES:
I already know whether or not it is a new entry, but I am hoping to have one "universal" query I can run rather than having to compose both versions... Thanks anyway.

HABTOM:
It looks like DUPLICATE KEY UPDATE is probably what I am looking for. I will go read about how it works and see if I can get it to do what I am hoping it will do. Thanks!