phpsqlmultiple-insert

add mutiple rows in database php?


I want to insert many rows in database through loops.( $product,$size, $quantity, $uom, $target_price) columns of one row.how to insert these type of mutilpe rows in database.and data.how to use for loop or other loop to enter detail record agasint serial no 1.

    if(isset($_POST['Submit_form']))
     {
     /*For Master Detail*/
     $serial_no=$_POST['serial_no'];
     $dated=$_POST['dated'];
     $ship_schedule=$_POST['ship_schedule'];
     $commission=$_POST['commission'];
     $customer_name=$_POST['customer_name'];
     $agnet_name=$_POST['agnet_name'];
     $remark=$_POST['remark'];
      /*For Detail*/
     $product=$_POST['product'];
     $size=$_POST['size'];
     $quantity=$_POST['quantity'];
     $uom=$_POST['uom'];
     $target_price=$_POST['target_price'];

    $sqli = "INSERT INTO inquiry_mst (dated,ship_schedule,commision,customer_id,agent_id,remarks)
VALUES ('$serial_no','$dated','$ship_schedule','$commission','$customer_name','$agnet_name','$remark')";
   $sqli=$mysqli->query($sqli) or die('Failed to connect'.$mysqli->error._LINE_);
   if($sqli)
   {
       foreach($choices as $choice => $values)
       {
         $sqli="INSERT INTO inquiry_dtl (serial_no, product_name,size,quantity,uom,target_price) 
         VALUES ($product,$size,$quantity,$uom,$target_price)";

       }
   }
}

Solution

  • You can use mysqli_multi_query for your request.

    <?php
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $dbname = "myDB";
    
    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    $sql = "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('John', 'Doe', 'john@example.com');";
    $sql .= "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('Mary', 'Moe', 'mary@example.com');";
    $sql .= "INSERT INTO MyGuests (firstname, lastname, email)
    VALUES ('Julie', 'Dooley', 'julie@example.com')";
    
    if ($conn->multi_query($sql) === TRUE) {
        echo "New records created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
    
    $conn->close();
    ?> 
    

    Source: http://www.w3schools.com/php/php_mysql_insert_multiple.asp

    or using the SQL Syntax(If you want one Query):

    INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);