user3182261
user3182261

Reputation: 271

Insert into multiple tables at once

I'm trying to insert data into multiple tables but I can't get it to work.

There is a projects table and a tag table. When I creat a new project I want the project data to go into the project table and the tags that I post in the same form to go into the tag table. I have no idea how to do this.

Also, the tag table uses the project_id from the project table. The id is set with auto increment. How can I use the id from the project table in the tag table when they are created at the same time?

This is the query I use to insert into the projects table:

 $query = mysqli_query($con, "INSERT INTO projects (project_title, project_summary, project_content, project_timestamp, photo_name, photo) VALUES('$title','$summary','$content','$time','$image_name','project_pics/$image_name')");

Upvotes: 0

Views: 408

Answers (5)

pilu
pilu

Reputation: 33

It is recommended that you put both queries in one transaction

Upvotes: 0

vignesh pbs
vignesh pbs

Reputation: 448

you can insert it by using two different queries for example-

$query1=my_query("insert into table1");
$id = insert_id();
$query2=my_query("insert into table2 (id) values ('$id')")

Upvotes: 1

devofash
devofash

Reputation: 328

You'd run your first query on table1, then get the insert id of the previous row and insert in table2

https://www.php.net/mysql_insert_id

hope this helps


Upvotes: 0

Steve Bals
Steve Bals

Reputation: 1979

$q1=mysql_query("insert into tab1");
$id = mysql_insert_id();
$q2=mysql_query("insert into tab2 (id) values ('$id')")

Upvotes: 3

user1652319
user1652319

Reputation: 103

I think you can achieve this by using mysqli to get the last inserted id

$mysqli->query($query);  
printf ("New Record has id %d.\n", $mysqli->insert_id);

Upvotes: 0

Related Questions