简体   繁体   中英

How to write multiple insert in multiple tables using the same form PHP

I have a problem with inserting data into two different tables: When a new member is created, it will be insert into member and grade tables after getting the id course from course table. I used INSERT for both of them at the same time with a multi query function but it doesn't work. Can you help me please?

The form:

<form>    
  <input type="text" name='m_fName'>
  <input type="text" name='m_lName'>
  <input type="text" name ='m_nId'>
</form>

Php

  $id = $re['c_id']; //to get id of course that I want to insert
  $sql="INSERT INTO member (m_fName, m_lName, m_nId) 
        VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');
        INSERT INTO grade(c_id,m_nId)
        VALUES( '$id','$_POST[m_nId]')";
  mysqli_multi_query($conn,$sql);

Answer above is the correct one, alternative way is the code below

$id = $re['c_id']; //to get id of course that I want to insert
  $sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
  $act = mysqli_query($conn,$sql);
if($act) {
   $sql2 = "INSERT INTO grade(c_id,m_nId)
  VALUES( '$id','$_POST[m_nId]')";
   $act2 = mysqli_query($conn,$sql2);
}
$id = $re['c_id'];
  $sql="INSERT INTO member (m_fName, m_lName, m_nId) VALUES('$_POST[m_fName]','$_POST[m_lName]','$_POST[m_nId]');";
  $sql .="INSERT INTO grade(c_id,m_nId) VALUES( '$id','$_POST[m_nId]')";

  if (mysqli_multi_query($conn, $sql)) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

Hope this will help. but try to first validate the posted data. check if isset .you did not show in the are you using post and the page you are posting your data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM