简体   繁体   中英

How to Get ID of the First Query and Use it to the 3rd Query?

I have a problem regarding SQL Query. I have 3 Insert queries in my code. the first query is with auto-increment ID.

INSERT INTO master_tbl

The second Insert will get the ID from 1st query using LAST_INSERT_ID() function.

INSERT INTO process (id_ref, process_id, hot_cold, temp) 
VALUES (LAST_INSERT_ID(), '4', '-', '12')

My problem is, I have third query which needed to use the ID generated in the 1st query as its id_ref also.

When I use the LAST_INSERT_ID() , the ID it gets was the ID of the second query.

Any suggestions on how can I still get the ID in the 1st query to use on 3rd?

You can declare the variable and store the first queries id in that variable and then use it wherever you want.

 After first query as you mentioned you are using the separate queries you can try using select to set the `Last insert id` into the variable and then use that variable as below,

   select @valuetoUse := LAST_INSERT_ID()

Or Other way is use select the to get the value in your code and then pass that value to insert as all other values. For getting value you can directly fire select

     SELECT LAST_INSERT_ID()

then in second query

   INSERT INTO process (id_ref, process_id, hot_cold, temp) 
   VALUES (valuetoUse , '4', '-', '12')

then again in the third query

   INSERT INTO thirdtable (id_ref, process_id, hot_cold, temp) 
   VALUES (valuetoUse , '4', '-', '12')

For more info on how to use user defined variables see here.

Functionality is same as told by @Coder of Code But with PHP

Try This

Create Connection

$conn = new mysqli($servername, $username, $password, $dbname);

First Insert into Table 1

INSERT INTO master_tbl

Then do

$sql = "SELECT MAX(id) as id from master_tbl";
$result = $conn->query($sql);
$row = $result->fetch_array(MYSQLI_NUM);
$latest_id=$row[0];

$sql = "INSERT INTO process (id_ref, process_id, hot_cold, temp)
 VALUES ($latest_id,'4','-','12')";

if ($conn->query($sql) === TRUE) 
{
    echo "New record created successfully";
}

$sql = "INSERT INTO table3 (id_ref , columns list)
 VALUES ($latest_id,other fields)";

if ($conn->query($sql) === TRUE) 
{
    echo "New record created successfully";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM