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.
Related
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);
}
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.
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.
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
Is it possible to have a table and insert data n a single row on two different occasion? I mean, I have a table with five column and on first data submission, i want to record data on only just two field on that table, and in different data submission on that same row, I would want to record data on those 3 remaining column that haven't been recorded with any data. What method should i use? INSERT or UPDATE? Or neither?
Sorry for my bad english and confusing way of asking question.
Code:
$query = ("SELECT q1 FROM grades where studentnumber = '$_POST[studentnumber]' && subjectcode = '$_POST[subjectcode]' ");
$result=mysql_query($query);
if($result)
{
if(mysql_num_rows($result) ==1)
{
$sql=mysql_query("UPDATE grades SET q1 = '$_POST[q1]' where studentnumber = '$_POST[studentnumber]' AND subjectcode = '$_POST[subjectcode]'");
if($sql)
{
echo "<script type='text/javascript'>alert('Password successfully changed'); location.href = 'cvsu-sis_grades.php';</script>";
}
}
}
else
{
echo "<script type='text/javascript'>alert('Record Does not Exist'); location.href = 'cvsu-sis_grades.php';</script>";
}
i omitted some columns just to make the coed shorter but most likely it is the same. just a series of q1, q2, ...
The first query should be an INSERT, then you can get the last inserted id and do an UPDATE query
You can use INSERT for first two columns, and get your inserted id using mysql_insert_id() (only if your primary key column name is "id") and using this you can update your remaining three columns using UPDATE
First of all you have to make sure, that when you insert the 2 fields on your first INSERT, the fields you leave empty are allowed to be NULL!
You have to INSERTthe first data into the table and later on, when you want to add the remaining fields, you have to UPDATE that row. Make sure that, when you UPDATE, you are using a WHERE-constraint (e.g. with the 2 fields already entered), otherwise all rows will be updated!