【问题标题】:How insert multiple rows in mysql table with php array? [duplicate]如何使用php数组在mysql表中插入多行? [复制]
【发布时间】:2014-04-29 10:59:44
【问题描述】:

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

我想插入到 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 行有数据 > 所有 4 行都已保存 ||第 1 行为空,第 2 到第 3 行包含数据 > 仅保存第 2 行和第 3 行,不保存第 4 行||第 2 行只有数据,其他都是空的 > 数据未保存 ||第 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);
    }


?>

【问题讨论】:

  • 我希望我的插入查询检查所有行并在行被填充时选择收集数据。如果没有移动到下一行。感谢您的任何建议
  • 我在阅读您的帖子时迷路了,但我建议您查看for loops :-)
  • 另外,我在 php 错误日志中得到了这个:PHP 注意:未定义索引:part_id 在第 4 行(第 4 行:是 $ids = mysqli_real_escape_string($con,($_POST['part_id' ]));) PHP 警告:mysqli_real_escape_string() 期望参数 2 是字符串,第 5 行中给出的数组(第 5 行:是 $quantities = mysqli_real_escape_string($con,($_POST['quantity']));) 'code 'PHP 注意:未初始化的字符串偏移量:第 14 行中的 0(第 14 行为:"part_id" => $ids[$i], )'/code'

标签: php mysql


【解决方案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】:
  1. 使用 array_map 正确清理输入
  2. 在添加到数组之前检查输入
  3. 只有在要添加任何内容时才运行 SQL

使用以下代码:

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

【讨论】:

  • 我添加了 echo $sql;在 $sql 构造之后并添加了 mysqli_error($con);这是我得到的: INSERT INTO oz2ts_custompc_details (part_id, quantity, price) VALUES ('', '', '') ;成功插入:1
  • 另外在错误日志中,我有: PHP Notice: Undefined index: part_id in on line 4 (line 4: is $ids = mysqli_real_escape_string($con,($_POST['part_id']) );)
  • PHP 警告:mysqli_real_escape_string() 期望参数 2 是字符串,第 5 行中给出的数组(第 5 行:是 $quantities = mysqli_real_escape_string($con,($_POST['quantity'])); )
  • PHP 注意:未初始化的字符串偏移量:第 14 行为 0(第 14 行为:"part_id" => $ids[$i], )
  • 谢谢,但我收到了这个错误:PHP 警告:mysqli_real_escape_string() 只需要 2 个参数,这里有 1 个参数 > $ids = array_map('mysqli_real_escape_string', $_POST['part_id']);未插入任何行
【解决方案3】:

以下是插入数据时的基本问题处理示例。包含在错误检查中的是

  1. 确认我们收到了所有 3 个字段 - part_id、数量和价格
  2. 如果part_id为3行,则数量和价格必须为3行
  3. 通过准备 INSERT 语句来增加安全性
  4. 将变量绑定到准备好的语句
  5. 只选择输入了所有 3 个字段(part_id、数量和价格)并且它们是有效数字的行

接收 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;
}

?>

【讨论】:

  • 谢谢zfus。上面的代码仅在所有行都填满时才有效。当有空行时,它将停在: 2 个针对 price_id 的字段,但针对数量或价格收到了不同数量的字段。请确保part_id、数量和价格具有相同数量的字段。退出。
  • 普通表单将包含大约 15 行,并且并非总是会全部填写。有空行时如何获取代码以继续事件?
  • 嗨@user3412978,我在goo.gl/t7gWXk 上运行了这个确切的代码,它适用于我所做的测试。你能在那里做一些数据输入进行测试并提供一个失败的用例吗?这将有助于改进我的代码示例。
  • 我删除了第一个出口;现在它将停在:price_id 收到了 2 个字段,但数量或价格收到了不同数量的字段。请确保part_id、数量和价格具有相同数量的字段。退出。由于缺少或无效的 part_id、数量或价格,条目 #1 将被忽略 由于缺少或无效的 part_id、数量或价格,条目 #2 将被忽略。但没有插入数据
  • 您是在使用我在评论中提供的 URL,还是在您自己的网页上尝试?
猜你喜欢
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 2016-02-04
  • 1970-01-01
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
相关资源
最近更新 更多