Jump to content

Insert One table ID to another for loop table column field.


ripon_81

Recommended Posts

Hi


I am very new to PHP & Mysql.


I am trying to insert values into two tables at the same time. One table will insert a single row and the other table will insert multiple records based on user insertion.


Everything is working well, but in my second table, 1st Table ID simply insert one time and rest of the values are inserting from 2nd table itself.


Now I want to insert the first table's ID Field value (auto-incrementing) to a specific column in the second table (only all last inserted rows).


 


Ripon.


 


Below is my Code:



<?php



$con = mysql_connect("localhost","root","aaa");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }


mysql_select_db("ccc", $con);


$PI_No = $_POST['PI_No'];
$PO_No = $_POST['PO_No'];


$qry = "INSERT INTO wm_order_entry (
Order_No,
PI_No,
PO_No) 


VALUES(
NULL,
  '$PI_No',
 '$PO_No')";
$result = @mysql_query($qry);




$val1=$_POST['Size'];
$val2=$_POST['Style'];
$val3=$_POST['Colour'];
$val4=$_POST['Season_Code'];
$val5=$_POST['Dept'];
$val6=$_POST['Sub_Item'];
$val7=$_POST['Item_Desc'];
$val8=$_POST['UPC'];
$val9=$_POST['Qty'];
$N = count($val1);
for($i=0; $i < $N; $i++)
{


$profile_query = "INSERT INTO order_entry(Size,
Style,
Colour,
Season_Code,
Dept,
Sub_Item,
Item_Desc,
UPC,
Qty,
Order_No
) VALUES( '$val1[$i]','$val2[$i]','$val3[$i]','$val4[$i]','$val5[$i]','$val6[$i]','$val7[$i]','$val8[$i]','$val9[$i]',LAST_INSERT_ID())";
$t_query=mysql_query($profile_query);
}
header("location: WMView.php");
mysql_close($con);
?>

Output is attached.

Here i want in my second row my Order_No should be 170 instead of 38.

post-169372-0-88389300-1404368817_thumb.jpg

after the first INSERT query, you can get the last inserted id that was used by that query and use that id as a value in the other INSERT query.

 

for the msyql_ functions, you would use mysql_insert_id().

 

however, the mysql_ functions are depreciated and you should not be writing any new code that uses them. you should be using either msyqli_ or PDO functions (which each have an equivalent last insert id property/method.)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.