get mysql ON DUPLICATE KEY UPDATE.. count of rows inserted and updated - php

Using below query to insert update records:
INSERT INTO table (col_a,col_b,col_c,col_d) VALUES (val_a,val_b,val_c,val_d) ON DUPLICATE KEY UPDATE col_d = VALUES(col_d)
mySQL reports:
1 row affected per insert,
2 rows affected per update,
0 rows affected per duplicate
Followed link : Getting number of rows inserted for ON DUPLICATE KEY UPDATE multiple insert?
but didn't get correct numbers for inserted and updates records.
Is there any way of returning the correct number of inserts, updates and rows skipped (duplicates)?

Thanks overflowers, i worked out on a way.. thanks mitksoft for help, used answer given by a user user3556345 on another post - MySQL on duplicate key update + affected row count
using mysql_info() getting actual records, duplicates and skipped rows and warnings if any
Code below:
list($rec, $dupes, $warns) = sscanf(mysql_info($link), "Records: %d Duplicates: %d Warnings: %d"); // courtesy of user at big lake dot com - php.net
$inserts = $total_rows_affected - ($dupes * 2);
$updates = ($total_rows_affected - $inserts)/2;
$skipped = $rec - ($inserts + $updates);
$total = $rec;

Related

in Codeigniter 3/mySQL count number of inserted rows and number of updated rows independently in bulk operations

I have a query built under Codeigniter 3 for bulk operations of rows insertion that in case of duplication of a main key or unique index updates the relative fields instead of inserting new ones. The code could appear as the following generic one
$query = '
INSERT INTO table_B (code, fieldB1, fieldB2, table_A_id)
VALUES
(val1.1, val1.2, val1.3, val1.4),
(val2.1, val2.2, val2.3, val2.4),
(val3.1, val3.2, val3.3, val3.4)
ON DUPLICATE KEY UPDATE
fieldB1 = VALUES(fieldB1)
fieldB2 = VALUES(fieldB2)
fieldB3 = VALUES(fieldB3)';
$query_res = $this->db->query($query);
provided that 'code' is a unique index. Is there a way to retrieve the number of affected rows in insertion operations and the number of rows affected by updating operations distinctively?

INSERT MULTIPLE ROWS in Gerund Table using Insert Into Select

I used INSERT INTO SELECT to copy values (multiple rows) from one table to another. Now, my problem is how do I insert rows with its corresponding IDs from different tables (since it's normalized) into a gerund table because it only outputs one row in my gerund table. What should I do to insert multiple rows and their corresponding IDs in the gerund table.
My code for the gerund table goes like this.
$insert = "INSERT INTO table1 SELECT * FROM sourcetable"; // where id1 is pk of table1.
$result =mysqli_query($conn,$insert)
$id1=mysqli_insert_id($conn);
Now table 1 has inserted multiple rows same as the other 2 tables.
Assuming id.. are the foreign keys
INSERT INTO gerundtable (pk, id1,id2,id3) VALUES ($id1,$id2,$id3);
My problem is it doesn't yield multiple rows.
According to MySql documentation:
For a multiple-row insert, LAST_INSERT_ID() and mysql_insert_id() actually return the AUTO_INCREMENT key from the first of the inserted rows. This enables multiple-row inserts to be reproduced correctly on other servers in a replication setup.
So, grab the number of records being copied, and the LAST_INSERT_ID() and you should be able to map exact IDs with each copied row.
In the lines of:
$mysqli->query("Insert Into dest_table Select * from source_table");
$n = $mysqli->affected_rows; // number of copied rows
$id1 = $mysqli->insert_id; // new ID of the first copied row
$id2 = $mysqli->insert_id + 1; // new ID of the second copied row
$id3 = $mysqli->insert_id + 2; // new ID of the third copied row
...
$mysqli->query("INSERT INTO gerundtable (pk, id1,id2,id3) VALUES ($id1,$id2,$id3)");
Thank you for trying to understand and also answering my question. I resolved my own code. I used while loop to get the ids of every row and didn't use INSERT INTO SELECT.
Here is the run down. SInce I'm just using my phone bare with my way posting.
$sqlselect = SELECT * FROM table1;
While($row=mysqli_fetch_array(table1){
$insertquery...
$id1=mysqli_insert_id($conn)
$insertgerundtable = INSERT INTO gerundtable VALUES ( $id1, $id2);
}

How to merge rows in MySQL database with 2 identical identifiers and 2 unique identifiers either using PHP or MySQL

Okay so this is my first question and I really have no idea how to ask it so I'm going to try and be as specific as possible. My website is an online game and for user inventories when it inserts a new item into the database
Table name "inventory"
Column names "inv_id", "inv_itemid", "inv_userid", "inv_qty"
and it does not add to the column inv_qty and populate properly instead it creates a new inv_id identifier and row for each item. I was wondering if there was a way for me to create a merge function via php to merge all items with the same inv_itemid and inv_userid while adding to the inv_qty colum and populating the inv_id
In my inventory.php file the inv_id column is used to let the user either equip the item or use it as the main variable.
I have seen this done and have tried many times and I just can't get it to work.
If it were a single key to check then you could have used 'ON DUPLICATE KEY UPDATE' of mysql like the following:
INSERT INTO table(field1, field2, field3, ..)
VALUES (val1, val2, val3, ...)
ON DUPLICATE KEY
UPDATE field3='*'
But in your case there is a combination to consider.
If "inv_id", "inv_itemid", "inv_userid" mathces then UPDATE, otherwise INSERT.
One way to achieve this using only mysql in a single query is to create & use a Stored Procedure.
But using php you can achieve this in 2 query. First query is to determine if the combination exists. Then based on this run the next Insert or Update query.
Please check the following example:
$sql1 = SELECT * FROM inventory WHERE inv_id='$inv_id', inv_itemid='$inv_itemid', inv_userid='$inv_userid'
// Execute $sql1 and get the result.
IF result empty, then INSERT:
$sql2 = INSERT INTO inventory ....
otherwise UPDATE.
$sql2 = UPDATE inventory SET inv_qty=(inv_qty + $update_qty) WHERE inv_id='$inv_id', inv_itemid='$inv_itemid', inv_userid='$inv_userid'
About:
Would there be a way to write a php function at the top of the inventory page for my users to click to merge them
Please check with the following php function.
By calling with param: UserID, it will create a new entry with sum of the inv_qty, for each (inv_itemid + inv_userid) combination and removes the previous duplicate entries of (inv_itemid + inv_userid) leaving the newly enterd: (inv_itemid + inv_userid + (SUM of inv_qty)).
Important, please keep a back up of the DB Table Data before running the function.
Please check the comments in the function and update where necessary based on your system, Like getting the last inserted inv_id.
function merger_fnc($user_id) {
// For Each Combination of: inv_itemid + inv_userid
// This function will Insert a new row in the inventory with the SUM of inv_qty
// And then will remove the previous single rows of: inv_itemid + inv_userid + inv_qty
// First get the distinct Items of the User(by UserID);
$inv_itemids = $db->query("SELECT DISTINCT(inv_itemid) FROM inventory WHERE inv_userid=".$user_id);
// Here $inv_itemids will hold all the distinct ItemIDs for the UserID;
foreach ($inv_itemids as $inv_item) {
// We will Insert A new row which will have the sum of 'inv_qty' for the inv_userid & inv_itemid;
$inv_itemid = $inv_item['inv_itemid'];
// I am not sure what type of result set your $db->query(...) returns. So I assumed it is associative array.
// If the result is an Array of objects, then please use: $inv_itemid = $inv_item->inv_itemid;
$insert_sql = "INSERT INTO inventory (inv_itemid, inv_userid, inv_qty) VALUES ('".$inv_itemid."', '".$user_id."', (SELECT SUM(inv_qty) FROM FROM inventory WHERE inv_userid=".$user_id."))";
$inv_itemids = $db->query($insert_sql);
$inserted_new_inventory_id = $db->insert_id;
// Please check the appropriate method for it in your $db class here.
// In mysqli, it is: mysqli_insert_id($db_conn); In PDO it is: $db_conn->lastInsertId();
// Last we remove the previous data of combination(inv_userid & inv_itemid) but leaving our last inserted row.
$delete_sql = "DELETE FROM inventory WHERE inv_id!='".$inserted_new_inventory_id."' AND inv_userid='".$user_id."' AND inv_itemid='".$inv_itemid."'";
$db->query($delete_sql);
}
}
If getting the last inserted inv_id is troublesome from $db(like inv_id is not defined as key in the table), you can try another approach:
Do another query and save the previous inv_id in an array, before the insertion.
After the insertion of the new entry with sum of qty, run a delete query to delete the previous single qty entries, like the following:
DELETE FROM inventory WHERE inv_id IN (3, 4, 7,...)
Here (3, 4, 7,...) are the previous inv_id for (inv_itemid + inv_userid) combination.

LAST_INSERT_ID() is unequal to $db->insert_id?

I have the following query:
$year = 2019;
$month = 6;
$stmt = $db->prepare('INSERT INTO officeRechNr (jahr,monat,zahl) VALUES (?,?,1) ON DUPLICATE KEY UPDATE zahl = LAST_INSERT_ID(zahl+1)');
$stmt->bind_param('ii', $year, $month);
$stmt->execute();
echo $db->insert_id;
echo '|';
$sql = 'SELECT LAST_INSERT_ID() as number';
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo $row['number'];
echo '<br>';
The table officeRechNr has the unique primary index ['jahr','monat'] and zahl is an index with autoincrement.
If the table officeRechNr is empty, and I execute the code 3 times, then the output is
1|0
2|2
3|3
...
Why is LAST_INSERT_ID() zero after insert, but correct after upgrade?
How do I need to change my query, so that both functions output the same number (1) after insert?
Edit: The purpose of the code is that I need for each invoice that is created in a specific year and month a third unique ascending number. So for example if we have 7 invoices in the year 2015 and month May (3),then I would have the folloing numbers
2015-3-1
2015-3-2
2015-3-3
2015-3-4
2015-3-5
2015-3-6
2015-3-7
So in the row in the database I have stored the current invoice number and with the SQL command presented above I can get the next number. The only reason why the column zahl is an autoincrement field is that the number is returned by insert_id (see https://dev.mysql.com/doc/refman/5.7/en/getting-unique-id.html). Its also necessary to get it through insert_id in case that people create simultaneously invoices.
The problem is that LAST_INSERT_ID(...); with an argument doesn't return the generated ID but instead set the given value in the "memory" of LAST_INSERT_ID() and returns it. So, in your first execution no auto incremented ID was generated (you provided the value by yourself) and LAST_INSERT_ID() return 0. In your following executions you save the value next+1 in the internal storage of LAST_INSERT_ID(), which returns the value. This behavior is described in the MySQL in 12.14 Information Functions:
If expr is given as an argument to LAST_INSERT_ID(), the value of the argument is returned by the function and is remembered as the next value to be returned by LAST_INSERT_ID().
In fact, you can skip the LAST_INSERT_ID() call and work without it.
INSERT INTO
officeRechNr (jahr,monat,zahl)
VALUES
(?,?,1)
ON DUPLICATE KEY UPDATE zahl = zahl+1
This will insert the row (with the given value) or increase the counter.
If you want the current counter for a given year and month you run a simple SELECT statement. Keep in mind that you might need transactions or locks because a different client could increase the counter before you fetched it with the SELECT statement.

Unable to loop through mysql_insert_id() for multiple entries

I'm retrieving last id of tbl_orderdetail(table 1) in order to add addon items entries into tbl_orderdetail_addon(table 2). Basically it should insert into (table 2) as per the number of ids received from (table 1). I'm using mysql_insert_id() for that.
i'm getting that right but the ids are not looping through. It inserts the same id of (table 1) for all entries in (table 2). Say that I have two entries in (table 1),obviously it should return 2 id's.And each id has 2 add on items .So in (table 2) there should be four entries with 2 different id's of (table 1). IN my case Im getting 4 entries of same id of (table 1).
Here's my coding:
$o_id_detail=mysql_insert_id();//(table 1) id
foreach($addon_price as $a_p=>$p)//
{
echo $a_p;
foreach($p as $m)
{
$addon_id= $m['id'];
echo $m['addon_name'];
echo $m['deposit'];
echo $m['ppd'];
echo $m['pp_eight'];
echo $m['pp_six'];
$addon_total=$m['deposit']+$m['ppd']+$m['pp_eight']+$m['pp_six'];
echo $addon_total;
$addon_detail="INSERT INTO tbl_orderdetail_addon (OrderID,addOns_id,addOns_price) VALUES ('$o_id_detail','$addon_id','$addon_total')";
if(!empty($addon_id))
{
mysql_query($addon_detail)or die(mysql_error());
}
}
}
Any help would be greatly appreciated.Thanks in advance.
Basically it should insert into (table 2) as per the number of ids received from (table 1)
mysql_insert_id() only returns a single int value. As described in the manual:
Retrieves the ID generated for an AUTO_INCREMENT column by the
previous query (usually INSERT).
You need to insert the first row to table1 then the corresponding rows in table2; insert the second row to table1 then the corresponding rows in table2; etc.
Pseudo-code to explain the previous paragraph:
foreach order_detail {
insert order_detail;
get last_insert_id;
foreach order_detail_addon {
insert order_detail_addon with last_insert_id;
}
}
Edited to add:
Your code is vulnerable to SQL Injection. Read this and also see what the PHP manual says about it.
And you should stop using the mysql_* functions.

Categories