Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How insert multiple rows in mysql table with php array? [duplicate]

Tags:

php

mysql

I need to insert entries to mysql table from the form below. 1-form contains many rows. 2-entry will not be always consecutive in the rows (meaning row 1 can be empty and next row not) 3-all rows containing entries should be saved in the db table.

i want to INSERT INTO oz2ts_custompc_details (part_id, quantity, price)

Here is my entry form (custompc_form2.php)

<!DOCTYPE html>
<html>
<body>

<form action="../subs/custompcorder2.php/" method="post" id="form">

            <p><input id="name" name="part_id[]"/> 
               <input type="text"  id="quantity" name="quantity[]"/>  
               <input id="name-data" type="text" name="price[]"/></p>

            <p><input id="name" name="part_id[]"/> 
               <input type="text" id="quantity" name="quantity[]"/>  
               <input id="name-data" type="text" name="price[]"/></p>

            <p><input id="name" name="part_id[]"/> 
               <input type="text" id="quantity" name="quantity[]"/> 
               <input id="name-data" type="text" name="price[]"/></p>

            <p><input id="name" name="part_id[]"/> 
               <input type="text" id="quantity" name="quantity[]"/> 
               <input id="name-data" type="text" name="price[]"/></p>   


    <input id="submit" type="submit" value="Submit Order" name="submission"/>


</form>
</body> 
</html>

here is What I came up with but still not working. here is the summary of how it is working: ||Rows 1 to 4 has data > all 4 are saved || row 1 is empty and rows 2 to 3 contains data > only rows 2 and 3 are saved not row 4|| Row 2 only has data all other are empty > Data not saved || Rows 2 and 3 has data > Row 2 only is saved

 <?php
include '../db/connect.php';


foreach (array('part_id', 'quantity', 'price') as $pos) {
foreach ($_POST[$pos] as $id => $row) {
    $_POST[$pos][$id] = mysqli_real_escape_string($con, $row);
}
}

$ids = $_POST['part_id'];
$quantities = $_POST['quantity'];
$prices =  $_POST['price'];

$items = array();

$size = count($ids);

for($i = 0 ; $i < $size ; $i++){
// Check for part id
if (empty($ids[$i]) || empty($quantities[$i]) || empty($prices[$i])) {
    continue;
}
$items[]=array(
    "part_id"     => $ids[$i], 
    "quantity"    => $quantities[$i],
    "price"       => $prices[$i]
);
}

if (!empty($items)) {
$values = array();
foreach($items as $item){
    $values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
}

$values = implode(", ", $values);

$sql = "INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES     {$values}    ;
" ;
$result = mysqli_query($con, $sql );
if ($result) {
    echo 'Successful inserts: ' . mysqli_affected_rows($con);
} else {
    echo 'query failed: ' . mysqli_error($con);  

}
}

?> 

The first is a simplified entry form. The reel entry form looks like this:

    <!DOCTYPE html>
    <html>
    <head></head>
    <body>

    <form action="../subs/custompcorder2.php/" method="post" id="form">

          <div id="orderwrap">
         <div id="orderheather">
        <select id="platform" name="platform">
        <option selected="selected" disabled="disabled">Select the 
                    platform</option>
        <option value="Intel">Intel</option>
        <option value="AMD">AMD</option>
       </select> 
    </div> 

       <div id="orderbody">

         <p><select id="part_id" name="part_id[]">
                        <option selected="selected" disabled="disabled">Choose part1 </option>
                 <?php  query() ?> 
                 < /select>
                         <input type="text" id="quantity" name="quantity[]"/> 
                         <input id="name-data" type="text" name="price[]"/></p>

         <p><select id="part_id" name="part_id[]">
                        <option selected="selected" disabled="disabled">Choose part2 </option>
                 <?php  query2() ?> 
                 < /select>
                         <input type="text" id="quantity" name="quantity[]"/> 
                         <input id="name-data" type="text" name="price[]"/></p> 

         <p><select id="part_id" name="part_id[]">
                        <option selected="selected" disabled="disabled">Choose part3 </option>
                 <?php  query3() ?> 
                 < /select>
                         <input type="text" id="quantity" name="quantity[]"/> 
                         <input id="name-data" type="text" name="price[]"/></p> 

         <p><select id="part_id" name="part_id[]">
                        <option selected="selected" disabled="disabled">Choose part4 </option>
                 <?php  query4() ?> 
                 < /select>
                         <input type="text" id="quantity" name="quantity[]"/> 
                         <input id="name-data" type="text" name="price[]"/></p>  



        <input id="submit" type="submit" value="Submit Order"name="submission"/>

       </div>
      </div>    
        </form>


      </body> 

     </html>

Here is the php page containing function query(),query1(),..

<?php
include '../db/connect.php';


function query(){
global $con; 
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
    echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
    }
}

function query2(){
global $con; 
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
    echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
    }
}


function query3(){
global $con; 
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
    echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
    }
}


function query4(){
global $con; 
$myData=mysqli_query($con,"SELECT * FROM oz2ts_mijoshop_product");
while($record=mysqli_fetch_array($myData)){
    echo'<option value="'.$record['product_id'].'">'.$record['model'].'</option>';
    }
}

function close(){
    mysqli_close($con);
    }


?>
like image 482
user3412978 Avatar asked Oct 16 '25 10:10

user3412978


1 Answers

  1. Sanitize input correctly using array_map
  2. Check for input before adding to array
  3. Only run SQL if anything to be added

Use the following code:

<?php
include '../db/connect.php';

foreach (array('part_id', 'quantity', 'price') as $pos) {
    foreach ($_POST[$pos] as $id => $row) {
        $_POST[$pos][$id] = mysqli_real_escape_string($con, $row);
    }
}

$ids = $_POST['part_id'];
$quantities = $_POST['quantity'];
$prices =  $_POST['price'];

$items = array();

$size = count($ids);

for($i = 0 ; $i < $size ; $i++){
    // Check for part id
    if (empty($ids[$i]) || empty($quantities[$i]) || empty($prices[$i])) {
        continue;
    }
    $items[] = array(
        "part_id"     => $ids[$i], 
        "quantity"    => $quantities[$i],
        "price"       => $prices[$i]
    );
}

if (!empty($items)) {
    $values = array();
    foreach($items as $item){
        $values[] = "('{$item['part_id']}', '{$item['quantity']}', '{$item['price']}')";
    }

    $values = implode(", ", $values);

    $sql = "INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES  {$values}    ;
    " ;
    $result = mysqli_query($con, $sql );
    if ($result) {
        echo 'Successful inserts: ' . mysqli_affected_rows($con);
    } else {
        echo 'query failed: ' . mysqli_error($con);
    }
}
like image 124
Aziz Saleh Avatar answered Oct 19 '25 01:10

Aziz Saleh