简体   繁体   中英

How insert multiple rows in mysql table with php array?

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);
    }


?>
  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);
    }
}

Here is a rough code, modify indeces by your own needs.

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

$items = array();

$size = count($names);

for($i = 0 ; $i < $size ; $i++){
  $items[$i] = array(
     "part_id"     => $ids[$i], 
     "quantity"    => $quantities[$i], 
     "price"       => $prices[$i]
  );
}


$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} ;
" ;

Here's an example of basic issue handling while inserting data. Included in error checks are

  1. Confirm that we received all 3 fields - part_id, quantity and price
  2. If there were 3 rows of part_id, there must be 3 rows of quantity and price
  3. Add safety by preparing INSERT statement
  4. Bind variables to the prepared statements
  5. Pick up only those rows in which all 3 fields (part_id, quantity and price) were entered, and that they were valid numbers

Code that receives POST

<?php

ini_set('display_errors', 'On');
error_reporting(E_ALL);

// debug information. Let's find what the page is receiving
echo '<pre>', print_r($_POST, true), '</pre>';

$postedData = $_POST;

// confirm that we received all 3 fields - part_id, quantity, price
$fieldsReceived = true;
if (   !confirmFields('part_id') 
    || !confirmFields('quantity')
    || !confirmFields('price')
) {
    echo 'part_id, quantity or price has not been received. Exiting.';
    exit;
}

// confirm that each of them have identical item-count
if (   count($postedData['part_id']) !== count($postedData['quantity'])
    || count($postedData['part_id']) !== count($postedData['price'])
) {
    echo count($postedData['price_id']) . 
        ' fields received for price_id, but different number of fields 
        were received for quantity or price. Please ensure that part_id,
        quantity and price have the same number of fields. Exiting.';
    exit;
}

// establish connection using mysqli_connect
$connection = mysqli_connect('localhost', 'user', 'pass', 'selected_db');

// prepare an insert statement
$sql = 'insert into oz2ts_custompc_details 
        (part_id, quantity, price) values 
        (?, ?, ?)';
$statement = mysqli_prepare($connection, $sql);

// bind integer, integer, double to the parameters in insert statement
// corresponding to the question marks
$part = 0;
$qty = 0;
$prc = 0.0000;
mysqli_stmt_bind_param($statement, 'iid', $part, $qty, $prc);

// loop through received data and only insert those that have valid values
// in part_id, quantity and price
$partsReceived = count($postedData['part_id']);
for ($i = 0; $i < $partsReceived; $i++) {

    // if drop down boxes are used and default value for part is
    // Choose part, let's see if user left the selection to default
    // and ignore that line
    if (strpos($postedData['part_id'][$i], 'Choose part') !== false) {
        continue;
    }

    // do we have numeric data in current line?
    // although not done here, one can check if part_id is integer (is_int)
    // quantity is_int and price is_float before proceeding further
    if (   !is_numeric($postedData['part_id'][$i])
        || !is_numeric($postedData['quantity'][$i])
        || !is_numeric($postedData['price'][$i])
    ) {
        echo '<p>Entry # ' . ($i + 1) . '
            will be ignored because of missing 
            or invalid part_id, quantity, or price</p>';
        continue;
    }

    // update bind parameters
    $part = $postedData['part_id'][$i];
    $qty = $postedData['quantity'][$i];
    $prc = $postedData['price'][$i];

    // execute statement and move on to the next one
    try {
        mysqli_stmt_execute($statement);
        echo '<p>Inserted part_id ' . $postedData['part_id'][$i] . '</p>';
    } catch (Exception $e) {
        echo '<p>Could not enter data with part_id '
            . $postedData['part_id'][$i] . '<br>' 
            . 'Error ' . $e->getMessage() . '</p>';
    }
}


// --------------------------
//        FUNCTIONS
// --------------------------

/**
 * Confirm that we received part_id, quantity and price from POST
 *
 * @param string $fieldName Name of the field to verify
 * 
 * @return bool True if fieldname is set as an array; False otherwise
 */
function confirmFields($fieldName) 
{
    global $postedData;
    return 
        (!isset($postedData[$fieldName])) 
        && !is_array($postedData[$fieldName]) ? false : true;
}

?>

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