ripon_81 Posted July 3, 2014 Share Posted July 3, 2014 (edited) 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. Edited July 3, 2014 by mac_gyver code tags please Quote Link to comment https://forums.phpfreaks.com/topic/289397-insert-one-table-id-to-another-for-loop-table-column-field/ Share on other sites More sharing options...
mac_gyver Posted July 3, 2014 Share Posted July 3, 2014 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.) Quote Link to comment https://forums.phpfreaks.com/topic/289397-insert-one-table-id-to-another-for-loop-table-column-field/#findComment-1483688 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.