Reputation: 271
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
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
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
Reputation: 1979
$q1=mysql_query("insert into tab1");
$id = mysql_insert_id();
$q2=mysql_query("insert into tab2 (id) values ('$id')")
Upvotes: 3
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