简体   繁体   中英

How to Insert / Update a Row in MySQL / PHP At The Same Time

I want to insert into a MySQL row if the row doesn't exist, or update it if it does exist.

Something like this:

$sqlQuery = "INSERT INTO table (Value1, Value2) VALUES ('$var1', '$var2') WHERE UniqueKey='$id'";

Is something like that possible?

INSERT INTO table (UniqueKey,Value1, Value2) VALUES ('$id','$var1', '$var2') 
ON DUPLICATE KEY UPDATE Value1 = '$var1',Value2 = '$var1';

User MySQL's REPLACE command:

$sqlQuery = "REPLACE INTO table (id, Value1, Value2) VALUES ('$id', '$var1', '$var2')";

It works the same as a normal INSERT, but if the primary key (in you case 'id') matches then it will replace all the values specified.

replace into table (UniqueKey,Value1,Value2) values ('$id','$var1','$var2');

replace is similar to insert, however if the unique key exists in table, it will delete first, and than insert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM