[Php][Mysql] How to Insert Data in 2 Tables At Same Time

[PHP][MySQL] How to insert data in 2 tables at same time?

You can get the value of tb1_id using mysqli_insert_id(), and then insert that into tb2:

$sqla = "INSERT INTO tb1 (tb1_title, tb1_cat) VALUES ('$tb1_title', '$tb1_cat')";
if (mysqli_query($db, $sqla)) {
$tb1_id = mysqli_insert_id($db);
$sqlb = "INSERT INTO tb2 (tb2_title, tb2_doc, id_tb1) VALUES ('$tb2_title', '$tb2_doc', $tb1_id)";
mysqli_query($db, $sqlb);
}

Mysql insert into two tables at same time

You could use mysqli::multi_query

$query  = "insert into games (games_title,games_date,games_author,games_image,games_keywords,games_link,games_content) values ('$games_title','$games_date','$games_author','$games_image','$games_keywords','$games_link','$games_content');";
$query .= "insert into archive (title, pub_date) values ('$games_title','$games_date')";

if (mysqli_multi_query($connect, $query)) {

echo "Data in two tables successfully inserted.";
}

Trying to Insert data to multiple tables in single query in php

Thomas i try your query u should modify and try this query:

Code :

      $sql = "INSERT INTO contacts (firstName,lastName,nickName,cellNumber,homeNumber,workNumber) VALUES ($firstName,$lastName,$nickName,$cellNumber,$homeNumber,$workNumber) " ; "INSERT INTO address(street,city,state,country) VALUES($street,$city,$state,$country)"; "INSERT INTO contacts (email,birthday,memo)
values($email,$birthday,$memo)";

I think it should be must helpful.

How to use Insert query with multiple tables at a same time?

No, you can't insert into multiple tables in one MySQL command. You can however use transactions.

Check this : MySQL Insert into multiple tables? (Database normalization?)



Related Topics



Leave a reply



Submit