getting mysql_insert_id() while using ON DUPLICATE KEY UPDATE with PHP - php

I've found a few answers for this using mySQL alone, but I was hoping someone could show me a way to get the ID of the last inserted or updated row of a mysql DB when using PHP to handle the inserts/updates.
Currently I have something like this, where column3 is a unique key, and there's also an id column that's an autoincremented primary key:
$query ="INSERT INTO TABLE (column1, column2, column3) VALUES (value1, value2, value3) ON DUPLICATE KEY UPDATE SET column1=value1, column2=value2, column3=value3";
mysql_query($query);
$my_id = mysql_insert_id();
$my_id is correct on INSERT, but incorrect when it's updating a row (ON DUPLICATE KEY UPDATE).
I have seen several posts with people advising that you use something like
INSERT INTO table (a) VALUES (0) ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id)
to get a valid ID value when the ON DUPLICATE KEY is invoked-- but will this return that valid ID to the PHP mysql_insert_id() function?

Here's the answer, as suggested by Alexandre:
when you use the id=LAST_INSERT_ID(id) it sets the value of mysql_insert_id = the updated ID-- so your final code should look like:
<?
$query = mysql_query("
INSERT INTO table (column1, column2, column3)
VALUES (value1, value2, value3)
ON DUPLICATE KEY UPDATE
column1 = value1,
column2 = value2,
column3 = value3,
id=LAST_INSERT_ID(id)
");
$my_id = mysql_insert_id();
This will return the right value for $my_id regardless of update or insert.

You could check if the Query was an insert or an update ( mysql_affected_rows(); returns 1 on insert and 2 on update).
If it was an insert use mysql_insert_id, if it was an update you'd need another Query.
<?php
$query ="INSERT INTO TABLE (column1, column2, column3) VALUES (value1, value2, value3) ON DUPLICATE KEY UPDATE SET column1=value1, column2=value2, column3=value3";
mysql_query($query);
if(mysql_affected_rows() == 1) { $id = mysql_insert_id(); }
else { // select ...
}
?>
I know it's not excatly what your looking for but it's the best i could come up with

Although not using mysql_insert_id() and ON DUPLICATE KEY UPDATE, alternative great way to get the value of any field when updating another found here:
UPDATE table SET id=(#tempid:=id) , .... LIMIT 1;
SELECT #tempid;
I used it having table with (id,status) 'id' primary index auto-increment, and 'status' was the field upon which update was made, but i needed to get 'id' of the updated row. This solution also proof to race conditions as mysql_insert_id().

This is my solution where you put the data into a single array and it's automatically duplicated/populated into the "INSERT INTO .. ON DUPLICATE UPDATE .. " query.
It's great for maintainability, and if you want you can make it a function / method too.
// save to db:
$qData = [
"id" => mysql_real_escape_string($email_id),
"synd_id" => mysql_real_escape_string($synd_id),
"campaign_id" => mysql_real_escape_string($campaign_id),
"event_id" => mysql_real_escape_string($event_id),
"user_id" => mysql_real_escape_string($user_id),
"campaign_name" => mysql_real_escape_string($campaign_name),
"subject" => mysql_real_escape_string($subject),
"from_name"=> mysql_real_escape_string($from_name),
"from_email"=> mysql_real_escape_string($from),
"content"=> mysql_real_escape_string($html),
"link_to_template" => mysql_real_escape_string($hash),
"ext_campaign_id" => mysql_real_escape_string($ext_campaign_id),
"ext_list_id"=> mysql_real_escape_string($ext_list_id),
];
$q = "INSERT INTO email_campaigns (".
// i.e create a string like `id`, `synd_id`, `campaign_id`.. with linebreaks for readability
implode(", \n", array_map(function($k){ return "`$k`"; }, array_keys($qData)))
.")
VALUES (".
// i.e '20', '532', '600' ..
implode(", \n", array_map(function($v){ return "'$v'"; }, array_values($qData)))
." ) ON DUPLICATE KEY UPDATE ".
// i.e `synd_id`='532', `campaign_id`='600' ...
// id & link_to_template table keys are excluded based on the array below
implode(", \n", array_filter(array_map(function($k, $v){ if(!in_array($k, ['id', 'link_to_template']) ) return "`$k`='$v'" ; }, array_keys($qData), array_values($qData)))) ;

Related

$wpdb -> changing multiple INSERT queries into a single query

I have two tables:
Central_Address
Address_ID - PK and Auto Increment
Central_Class_Location
Central_Location_ID - PK and Auto Increment
Address_ID_FK - Foreign key referencing Address_ID
I was able to use phpmyadmin to insert data in both tables, including the foreign key:
INSERT INTO Central_Address (Address_ID) VALUES ('');
INSERT INTO Central_Class_Location (Central_Location_ID, Address_ID) VALUES ('', LAST_INSERT_ID());
However, when I try to use Wordpress's $wpdb, it adds to Central_Address, but not Central_Class_Location
$wpdb->query("INSERT INTO Central_Address (Address_ID) VALUES ('');
INSERT INTO Central_Class_Location (Central_Location_ID, Address_ID) VALUES ('', LAST_INSERT_ID());");
Has anyone ever been able to make foreign keys with $wpdb?
First of all you have to insert in Central_Address from wordpress method which is as follows
1) Insert Central_Address
$table = $wpdb->prefix.'Central_Address';
$data = array('column1' => 'data one', 'column2' => 123);
$format = array('%s','%d');
$wpdb->insert($table,$data,$format);
2) after then get database last inserted id using $wpdb->insert_id and run to insert second table query
$last_address_id = $wpdb->insert_id;
$central_class_location_table = $wpdb->prefix.'Central_Class_Location';
$data = array('Address_ID' => $last_address_id, 'column2' => 123);
$format = array('%d','%d');
$wpdb->insert($central_class_location_table, $data, $format);
I think it may have helped you

Trying to insert and update both in one query but not working

I have tried both insert and update in one query but not getting output.
DB::table('tablename')->update(
['email' => 'john#example.com', 'name' => 'John'],
['votes' => '2']->insert(
['email' => 'john#example.com', 'name' => 'John']
);
How can I run a query that will work for both.
You can not update and insert in one query because they are different things.
Sql update query works with where clause for example where id=3 updates where
some column of row which id equal to 3. https://www.w3schools.com/sql/sql_update.asp
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
But insert query is for inserting records to database.
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
And You use Laravel Eloquent.
$update = DB::table('some_table')->where('some_colname', 'some_value')->update([...]);
$insert = DB::table('some_table')->insert([...]);
https://laravel.com/docs/6.x/queries
In laravel updateOrInsert function inserts or updates a record matching the attributes, and fill it with values.
For example :
$attributes=['email'=>'john#example.com','name'=>'John'];
$values=['email'=>'john#example.com','name' =>'John','votes'=>'2'];
DB::table('table name')->updateOrInsert($attributes,$values);
Here with $attributes it is checking if the row exists or not, if exists it will update the row with $values, and if it doesn't exists it will insert $values.

UPDATE if ID already exists? [duplicate]

I've seen the following (using the VALUES option):
$query = "INSERT INTO $table (column-1, column-2, column-3) VALUES ('value-1', 'value-2', 'value-3') ON DUPLICATE KEY UPDATE SET column1 = value1, column2 = value2, column3 = value3, ID=LAST_INSERT_ID(ID)";
... but I can't figure how to add ON DUPLICATE KEY UPDATE to what I'm using:
$query = "INSERT INTO $table SET
column-1 ='value-1',
column-2 ='value-2',
column-3 ='value-3'
";
e.g.:, pseudo-code
$query = "INSERT INTO $table SET
column-1 ='value-1',
column-2 ='value-2',
column-3 ='value-3'
ON DUPLICATE KEY UPDATE SET
column1 = value1,
column2 = value2,
column3 = value3,
$id=LAST_INSERT_ID(id)";
$my_id = mysql_insert_id();
";
I would find the latter easier to read. Would appreciate clarification, didn't find an example in the manual.
cheers
I've used ON DUPLICATE KEY UPDATE a lot. For some situations it's non-standard SQL extension that's really worth using.
First, you need to make sure you have a unique key constraint in place. The ON DUPLICATE KEY UPDATE function only kicks in if there would've been a unique key violation.
Here's a commonly used format:
$query = "INSERT INTO $table (column1, column2, column3)
VALUES ('value-1', 'value-2', 'value-3')
ON DUPLICATE KEY UPDATE
column1 = values(column1),
column2 = values(column2),
column3 = values(column3);"
column1 = values(column1) means "Update column1 with the value that would have been inserted if the query hadn't hit the duplicate key violation." In other words, it just means update column1 to what it would've been had the insert worked.
Looking at this code, it doesn't seem correct that you're updating all three of the columns you're trying to insert. Which of the columns has a unique constraint on it?
EDIT: Modify based on 'SET' format of mysql insert statement per the question from the OP.
Basically to use ON DUPLICATE KEY UPDATE, you just write the insert statement as you normally would, but add the ON DUPLICATE KEY UPDATE clause tacked onto the end. I believe it should work like this:
INSERT INTO $table
set column1 = 'value-1',
column2 = 'value-2',
column3 = 'value-3'
ON DUPLICATE KEY UPDATE
column1 = values(column1),
column2 = values(column2),
column3 = values(column3);
Again, one of the columns you're inserting has to have a unique index (or a combination of the columns). That can be because one of them is the primary key or because there is a unique index on the table.
Have you tried using REPLACE INTO instead?
http://www.mysqlperformanceblog.com/2007/01/18/insert-on-duplicate-key-update-and-replace-into/

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.

Can I use ON DUPLICATE KEY UPDATE with an INSERT query using the SET option?

I've seen the following (using the VALUES option):
$query = "INSERT INTO $table (column-1, column-2, column-3) VALUES ('value-1', 'value-2', 'value-3') ON DUPLICATE KEY UPDATE SET column1 = value1, column2 = value2, column3 = value3, ID=LAST_INSERT_ID(ID)";
... but I can't figure how to add ON DUPLICATE KEY UPDATE to what I'm using:
$query = "INSERT INTO $table SET
column-1 ='value-1',
column-2 ='value-2',
column-3 ='value-3'
";
e.g.:, pseudo-code
$query = "INSERT INTO $table SET
column-1 ='value-1',
column-2 ='value-2',
column-3 ='value-3'
ON DUPLICATE KEY UPDATE SET
column1 = value1,
column2 = value2,
column3 = value3,
$id=LAST_INSERT_ID(id)";
$my_id = mysql_insert_id();
";
I would find the latter easier to read. Would appreciate clarification, didn't find an example in the manual.
cheers
I've used ON DUPLICATE KEY UPDATE a lot. For some situations it's non-standard SQL extension that's really worth using.
First, you need to make sure you have a unique key constraint in place. The ON DUPLICATE KEY UPDATE function only kicks in if there would've been a unique key violation.
Here's a commonly used format:
$query = "INSERT INTO $table (column1, column2, column3)
VALUES ('value-1', 'value-2', 'value-3')
ON DUPLICATE KEY UPDATE
column1 = values(column1),
column2 = values(column2),
column3 = values(column3);"
column1 = values(column1) means "Update column1 with the value that would have been inserted if the query hadn't hit the duplicate key violation." In other words, it just means update column1 to what it would've been had the insert worked.
Looking at this code, it doesn't seem correct that you're updating all three of the columns you're trying to insert. Which of the columns has a unique constraint on it?
EDIT: Modify based on 'SET' format of mysql insert statement per the question from the OP.
Basically to use ON DUPLICATE KEY UPDATE, you just write the insert statement as you normally would, but add the ON DUPLICATE KEY UPDATE clause tacked onto the end. I believe it should work like this:
INSERT INTO $table
set column1 = 'value-1',
column2 = 'value-2',
column3 = 'value-3'
ON DUPLICATE KEY UPDATE
column1 = values(column1),
column2 = values(column2),
column3 = values(column3);
Again, one of the columns you're inserting has to have a unique index (or a combination of the columns). That can be because one of them is the primary key or because there is a unique index on the table.
Have you tried using REPLACE INTO instead?
http://www.mysqlperformanceblog.com/2007/01/18/insert-on-duplicate-key-update-and-replace-into/

Categories