Skip to content
Advertisement

Inserting to multiple mysql table based on an primary key from first table

I am trying to write to two mysql tables.

Table 1: vehicles

JavaScript

The field vehicle_id is auto incremented. I need to use this field in the next table speed_log.

This is the other table that.

Table 2: speed_log

JavaScript

As above, the id is auto incremented but I need to pick the vehicle_id from the first table when the script runs. The vehicle_id in the second table is the foreign key.

This is my syntax for writing data to the table 1

JavaScript

Now my issues are two:

  1. How should I pick the vehicle_id from table 1.
  2. How will my insert statement go to write the data to table 2

Advertisement

Answer

This is a job for LAST_INSERT_ID() or its PDO variant.

Do something like this

JavaScript

Whatever you do, do not do anything like

JavaScript

because that is a notorious way of making a huge mess (race conditions) if more than one user is using your php program concurrently.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement