Inserting into two tables at same time


I have a form, while submitting this i need to store the values into two different tables in a database,Some values will store in a table and others will store in a another table. How can i write it’s query ?

For Example,

$sql=“INSERT INTO table1 (field1, field2, field3,field4)

$sql2=“INSERT INTO table2 (field5, field6, field7,field8)

For me like this, Only one $sql values are only inserting, $sql2 values are not inserting.

Thanks in Advance

Can you please show the code where the queries are sent to the database.

Be aware that you’re code that you’ve shown is vulnerable to an SQL Injection Attack. You should use Prepared Statements to prevent SQL Injection attacks. Have a read of this article from the PHP manual, it shows how to use prepared statements with PDO and also explains the principle. The Golden Rule is "Never trust any data that has been submitted by the user in any way, always sanitize it and “escape” it or even better, use Prepared Statements.

It’s from a knockout js, it’s something like below,

data: “field1=” + viewModel.field1() + “& field2=” + viewModel.field2() + “& field3=” + viewModel.field3() + “& field4=” + viewModel.field4() + “& field5=” + viewModel.field5() + “& field6=” + viewModel.field6() + “& field7=” + viewModel.field7,

I have updated my query like below, now it’s inserting into 2 tables, but the problem is some times i need more than once, means 2, or 3 times need to execute the “$sql2” query. But it’s only inserting once. How can i fix his ?

mysqli_autocommit($con, false);
$flag = true;

$sql="INSERT INTO table1 (column1, column2, column3,column4)

$sql2 = "INSERT INTO table2   (column5,column6,column7,column8) VALUES ('$_POST[field5]','$_POST[field6]','$_POST[field7]','$_POST[field8]')";

$result = mysqli_query($con, $sql);

if (!$result) {
   $flag = false;
   echo "Error details: " . mysqli_error($con) . ". ";
$result = mysqli_query($con, $sql2);
if (!$result) {
    $flag = false;
    echo "Error details: " . mysqli_error($con) . ". ";

if ($flag) {

   echo "All queries were executed successfully";

} else {
   echo "All queries were rolled back";