How do I loop last insert id - php

I have these set of queries, its working fine except that I'm only able to get one value from LAST_INSERT_ID() in my UPDATE query;
$query .= "INSERT into itemorders
(itemID,colourID,itemName,itemSize,itemPrice,quantity,orderID) SELECT
itemID,colourID,itemName,itemSize,itemPrice,quantity,
LAST_INSERT_ID() FROM mycart WHERE email='".$email."'; ";
$query .= "UPDATE CatalogueItemsSize p
INNER JOIN itemorders i ON p.size = i.itemSize AND p.colourID =
i.colourID SET p.quantity = p.quantity - i.quantity WHERE i.id =
LAST_INSERT_ID();";
I understand that it can only retrieve the last single inserted row, how do I loop this so that I am able to catch all the values inserted in the first query?
Currently it is only subtracting quantity one row from the CatalogueItemsSize Table.

The Last insert ID ONLY returns the LAST inserted record's ID.
If you need to get the last insert ID for each record inserted, you will need to run your SELECT statement, get the results, then run an INSERT statement for each record in your SELECT and then run your update with the last_insert_id()
Also, in your INSERT statement, the last_insert_id() there will likely either cause an error or at the very least have unintended consequences.

Related

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);
}

Insert data with MAX(id) and values of status at the same time

I was trying with this code but it didn't work. it's always get the MAX(eq_no) as 0
$sql1 =mysqli_query($con, "SELECT MAX(eq_no) AS val FROM tech_add_equip");
$sql2 = "INSERT INTO time (eq_no,status_no) VALUES ('$val', 4 );";
if (!mysqli_query($con,$sql2)) {
die('Error: ' . mysqli_error($con)); };
Finally, after I try with this code, it inserts in the right number of MAX(eq_no) but i still cant insert the values of status_no
INSERT INTO time (eq_no) SELECT MAX(eq_no) AS vale FROM tech_add_equip
Could you suggest me what did i missing in the code?
Thank you for your helping
One row returned from SELECT a,b,c statement in sub query is equivalent to set of values that is otherwise hardcoded as ('a-value','b-value','c-value')*. You can hardcode a value within select as well:
INSERT INTO time (eq_no, status_no)
SELECT MAX(eq_no), 4
FROM tech_add_equip
No need for aliases within select - order of columns matters.
*) One row result can be used for IN() clause. Another row would become set of values after comma - can't be uset for IN(), but it works ok for INSERT
('row1-a-value', 'row1-b-value'), ('row2-a-value', 'row2-b-value')
$max = SELECT MAX( customer_id ) FROM customers;
INSERT INTO customers( customer_id, statusno )
VALUES ($max , 4)

Get sql Id and insert it into another query instantly

I have two tables first called messages and the other called messages_reply.
I used this code to insert into messages table:
$query = "INSERT INTO `messages` VALUES('', '$id', '$otherId', '')";
$query_run = mysqli_query($connect, $query);
I have the first column auto_increment thats why I left it empty by writing ''
Now i want this auto_increment value that i have inserted to be inserted in the other table called messages_reply
Do I have to create another query to return it or there is an instant way to insert it here and there?
you have to select the last id on table messages first, then you can insert that last id + 1 into messages reply
$query_sel_last_id = "SELECT id FROM messages ORDER BY id desc LIMIT 1"; // select the last id
after that, you only need to insert to messages_reply, remember to plus the value
$query_sel_last_id + 1
EDIT: gordon's solution is better and simpler, LAST_INSERT_ID()

Inserting data into multiple tables not functioning correctly

I have the following two tables
Table player:
player_id (int)(primary)
player_name (varchar)
player_report_count (int)
Table report:
report_id (int)(primary)
player_id
report_description
report_location
Firstly I ask the user for the player_name and insert it into the player database. From here the player is given an id.
Then I tried to grab the value of the players report count and increment the current value by one (which isn't working).
This is followed by grabbing the playerId from the player table and then inserting into the corresponding column from the report table (also does not work).
When I insert some values into the database, the names, description and report are added to the database however the playerID remains at 0 for all entries and the player_report_count remains at a consistent 0.
What is the correct way to make these two features function? And also is there a more efficient way of doing this?
<?php
$records = array();
if(!empty($_POST)){
if(isset($_POST['player_name'],
$_POST['report_description'],
$_POST['report_location'])){
$player_name = trim($_POST['player_name']);
$report_description = trim($_POST['report_description']);
$report_location = trim($_POST['report_location']);
if(!empty($player_name) && !empty($report_description) && !empty($report_location)){
$insertPlayer = $db->prepare("
INSERT INTO player (player_name)
VALUES (?)
");
$insertPlayer->bind_param('s', $player_name);
$reportCount = $db->query("
UPDATE player
SET player_report_count = player_report_count + 1
WHERE
player_name = $player_name
");
$getPlayerId = $db->query("
SELECT player_id
FROM player
WHERE player_name = $player_name
");
$insertReport = $db->prepare("
INSERT INTO report (player_id, report_description, report_location)
VALUES (?, ?, ?)
");
$insertReport->bind_param('iss', $getPlayerId, $report_description, $report_location);
if($insertPlayer->execute()
&& $insertReport->execute()
){
header('Location: insert.php');
die();
}
}
}
Main issue here is you are getting player details before inserting it. $getPlayerId will return empty result always.
Please follow the order as follows.
Insert player details in to player table and get payerid with mysql_insert_id. After binding you need to execute to insert details to the table.
Then bind and execute insert report .
Then update the player table by incrementing report count with playerid which you got in step 1.
Note : use transactions when inserting multiple table. This will help you to rollback if any insert fails.
MySQL Query will return result object. Refer it from here https://stackoverflow.com/a/13791544/3045153
I hope it will help you
If you need to catch the ID of the last insterted player, This is the function you need if you're using PDO or if it's a custom Mysql Class, you need the return value of mysql_insert_id() (or mysqli_insert_id()) and then directly use it in the next INSERT INTO statement

How to know if new row was inserted, or if extant row was updated?

When using ON DUPLICATE KEY UPDATE in MySQL (with PDO), how can one check if an extant row was updated, or in a new row was inserted? I'm using PHP's PDO with a prepared query to insert:
$sql = "INSERT INTO some_table (f_name, l_name) ";
$sql.= "VALUES (:f_name, :l_name) ";
$sql.= "ON DUPLICATE KEY UPDATE ";
$sql.= " f_name = VALUES(f_name) ";
$sql.= " l_name = VALUES(l_name) ";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':f_name', 'Jeff');
$stmt->bindValue(':l_name', 'Atwood');
$stmt->execute();
Now I would like to output Updated! or Added! as appropriate. How can I check this?
You can check by checking number of affected rows.
Whenever a row is inserted it returns exactly same number as number of inserted rows. However, when it update, It multiply by 2 and return as affected rows.
For example,
If you are adding two row, and
Row is create: affected row would be 2
Row is updated: affected row would be 4
Reference: http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Also, to check number of affected rows you can use rowCount function ( http://in3.php.net/manual/en/pdostatement.rowcount.php )

Categories