Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MYSQL UPDATE if Exist or INSERT if not?

I have no idea if this is even remotely correct. I have a class where I would like to update the database if the fields currently exist or insert if they do not. The complication is that I am doing a joining 3 tables (set_colors, school_art, baseimage)

Any help would be really great.

Here is what I have:

public function set_layer_colors($value) {     global $db;      $result_array = mysql_query("     IF EXISTS(SELECT * FROM set_colors WHERE school_art_id = '{$value}')        UPDATE set_colors (school_art_id, baseimage_id, sub_folder, layer)         SELECT school_art.id, baseimage.id, baseimage.sub_folder, baseimage.layer         FROM school_art          JOIN baseimage ON baseimage.base_folder = school_art.series_code          WHERE baseimage.image_type = 'B' ORDER BY school_art.id       ELSE       INSERT INTO set_colors (school_art_id, baseimage_id, sub_folder, layer)         SELECT school_art.id, baseimage.id, baseimage.sub_folder, baseimage.layer         FROM school_art          JOIN baseimage ON baseimage.base_folder = school_art.series_code          WHERE baseimage.image_type = 'B' ORDER BY school_art.id          ");      return $result_array; } 
like image 328
GGcupie Avatar asked Jul 28 '11 01:07

GGcupie


People also ask

Does MySQL update insert if not exists?

Often you have the situation that you need to check if an table entry exists, before you can make an update. If it does not exist, you have to do an insert first. Unfortunately, this the 'ON DUPLICATE KEY' statement only works on PRIMARY KEY and UNIQUE columns.

Can we use insert instead of update?

No. Insert will only create a new row.

How do I use Upsert in MySQL?

We can perform MySQL UPSERT operation mainly in three ways, which are as follows: UPSERT using INSERT IGNORE. UPSERT using REPLACE. UPSERT using INSERT ON DUPLICATE KEY UPDATE.


1 Answers

I believe you are looking for the following syntax:

INSERT INTO <table> (field1, field2, field3, ...)  VALUES ('value1', 'value2','value3', ...) ON DUPLICATE KEY UPDATE field1='value1', field2='value2', field3='value3', ... 

Note: With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values.

MySQL Documentation: INSERT ... ON DUPLICATE KEY UPDATE Statement

like image 122
Tash Pemhiwa Avatar answered Sep 16 '22 11:09

Tash Pemhiwa