如何用php数组在mysql表中插入多行?

时间:2014-03-21 21:08:42

标签: php mysql

我需要从下面的表单中将条目插入到mysql表中。 1-form包含许多行。 2个条目在行中不总是连续的(意味着第1行可以为空而下一行不是) 3 - 包含条目的所有行都应保存在db表中。

我想INSTO INTO oz2ts_custompc_details(part_id,数量,价格)

这是我的报名表(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>

这是我想出的但仍然没有工作。 以下是它如何工作的摘要:||第1行到第4行有数据&gt;全部4个都保存了||第1行为空,第2行至第3行包含数据&gt;只保存第2行和第3行而不保存第4行||第2行只有其他所有数据都是空的&gt;数据未保存||第2行和第3行的数据>仅保存第2行

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

}
}

?> 

第一种是简化的报名表。卷轴输入表格如下所示:

    <!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>

这是包含函数query(),query1(),..

的php页面
<?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);
    }


?>

3 个答案:

答案 0 :(得分:5)

  1. 使用array_map正确清理输入
  2. 在添加到阵列
  3. 之前检查输入
  4. 如果要添加任何内容,则只运行SQL
  5. 使用以下代码:

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

答案 1 :(得分:1)

这是一个粗略的代码,根据您自己的需要修改indeces。

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

答案 2 :(得分:0)

这是插入数据时基本问题处理的一个示例。错误检查包括

  1. 确认我们已收到所有3个字段 - part_id,数量和价格
  2. 如果有3行part_id,则必须有3行数量和价格
  3. 通过准备INSERT语句来增加安全性
  4. 将变量绑定到准备好的陈述
  5. 仅选取输入了所有3个字段(part_id,数量和价格)的行,并且这些行是有效数字
  6. 接收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;
    }
    
    ?>