如何将多个动态行插入数据库

时间:2016-09-06 10:18:49

标签: php sql-server

我有一个使用php和jQuery创建的多行动态表。这是the link to view the table

一切正常,除非我将数据插入数据库,序列号不会按顺序保存。我的插入查询如下:

for($i = 0; $i < count($_POST['C_Objectives']); $i++)
{
    $sql = "INSERT INTO Appraisal_Objectives (Serial_Number,Objectives,Measures,Targets,subtotal,Corporate_Objective,Row_Number,ID) Values ('$formno','||<==','==','==','".$_POST['SubTotals'][$i]."','".$_POST['C_Objectives'][$i]."','".$_POST['SNo'][$i]."','$statement')";
    $stmt = sqlsrv_query($conn, $sql);
    if($stmt === false)
        die(print_r(sqlsrv_errors(), true));
    else
        echo " ";
}

for($i = 0; $i < count($_POST['Measures']); $i++)
{
    $sql = "INSERT INTO Appraisal_Objectives (Serial_Number,Objectives,Measures,Targets,Weightage,Row_Number,target_date,ID) VALUES ('$formno','".$_POST['Objectives'][$i]."','".$_POST['Measures'][$i]."','".$_POST['Achievement'][$i]."','".$_POST['Weightage_Target'][$i]."','".$_POST['SNo'][$i]."','".$_POST['Date_Target'][$i]."','$statement')"; 
    $stmt = sqlsrv_query($conn, $sql);
    if($stmt === false)
        die(print_r(sqlsrv_errors(), true));
    else
        echo " ";
}

序列号使用$_POST['SNo'][$i] 保存在 Row_Number列中。是否可以使用1个插入查询保存两个动态行,以便顺序保存序列号?

这是$_POST数组结果:

    [Row_Number] => Array
        (
            [0] => 1
            [1] => 2
        )

    [C_Objectives] => Array
        (
            [0] => A
            [1] => B
        )

    [Objectives] => Array
        (
            [0] => a1
            [1] => a4
            [2] => a7
            [3] => b1
        )

    [Measures] => Array
        (
            [0] => a2
            [1] => a5
            [2] => a8
            [3] => b2
        )

    [Achievement] => Array
        (
            [0] => a3
            [1] => a6
            [2] => a9
            [3] => b3
        )

    [Date_Target] => Array
        (
            [0] => 2016-09-09
            [1] => 2016-09-09
            [2] => 2016-09-09
            [3] => 2016-09-09
        )

    [Weightage_Target] => Array
        (
            [0] => 25
            [1] => 25
            [2] => 25
            [3] => 25
        )

    [SNo] => Array
        (
            [0] => 3
            [1] => 4
            [2] => 5
            [3] => 6
        )

    [SubTotals] => Array
        (
            [0] => 75
            [1] => 25
        )

    [GrandTotal] => 100
)

我也尝试使列自动递增,但是不按照在前端输入的顺序保存数据。

enter image description here

enter image description here

5 个答案:

答案 0 :(得分:5)

您的插入存在性能问题。请更改插入数据库的方式。您可以在一个查询中执行所有这些操作。即使你有第一个“for”的20个循环和第二个“for”的20个循环。

回答您提出的问题

如果您想按$ _POST ['SNo']顺序插入,请更改此行

for($i = 0; $i < count($_POST['C_Objectives']); $i++)

foreach($_POST['SNo'] as $i)

如果您需要一次插入多个插件,请执行以下操作:

INSERT INTO Appraisal_Objectives (Serial_Number,Objectives,...)
VALUES (Value1,Value2,...), (Value1,Value2,...)

这是你必须做的事

在您的代码中,您在6个查询中执行了相同的查询。它甚至可以超过6个更多$ _POST ['Measures']或$ _POST ['C_Objectives']数组长度。 您需要将它们放在一个查询中,当您不需要设置该值时,只需将其设置为列默认值即可。例如NULL

这样的事情:

//first we create $values array. it contains all values that you need to insert to the db
$values = array();
$j=0;

for($i = 0; $i < count($_POST['C_Objectives']); $i++){
    $values[$j]['Serial_Number'] = $formno;
    $values[$j]['Objectives'] = '||<==';
    //and fill others here
    //fill all cols that you wrote inside your query with the correct order
    $j++;
}

for($i = 0; $i < count($_POST['Measures']); $i++){
    $values[$j]['Serial_Number'] = $formno;
    $values[$j]['Objectives'] = $_POST['Objectives'][$i];
    //and fill others here
    //fill all cols that you wrote inside your query with the correct order
    $j++;
}

//now create (value1,value2,...),(value1,value2,...),...
$query = NULL;
foreach($values as $value){
    $tmp = NULL;
    foreach($value as $v){
        $tmp .= ($v=='')? 'NULL,' : "'$v',";
    }
    $tmp = rtrim($tmp,',');
    $query .= "($tmp),";
}
$query = rtrim($query,',');

//Now Insert
$sql = "INSERT INTO Appraisal_Objectives (Serial_Number,Objectives,...) VALUES $query";

在这个例子中,我只是告诉你如何做到这一点。请记住,您必须检查$ v并按列类型进行准备。检查是否设置了$_POST[KEY]和它的数组。如果$query为空,请勿插入数据库。

非常重要的代码

如果这不是您的原始代码,则没有问题,但如果是,请更改您在查询中使用$ _POST的方式。它的安全性很低。至少你需要在使用之前验证它们。

答案 1 :(得分:0)

是的,您可以在单个插入查询中插入。

        $arrMeasuresInsData = array();
        for($i = 0; $i < count($_POST['C_Objectives']); $i++) {
          $sql = "INSERT INTO Appraisal_Objectives (Serial_Number, Objectives, Measures, Targets, subtotal, Corporate_Objective, Row_Number, ID, Weightagen, target_date) 
          Values ('$formno',
                    '||<==',
                    '==',
                    '==',
                    '".$_POST['SubTotals'][$i]."',
                    '".$_POST['C_Objectives'][$i]."',
                    '".$_POST['SNo'][$i]."',
                    '$statement',
                    '',
                    '')";

            if(!empty($_POST['Measures'][$i])) {
                $arrMeasuresInsData[$i] = $_POST['Measures'][$i];
                $sql .= ",('$formno',
                        '".$_POST['Objectives'][$i]."',
                        '".$_POST['Measures'][$i]."',
                        '".$_POST['Achievement'][$i]."',
                        '',
                        '',             
                        '".$_POST['SNo'][$i]."',
                        '".$_POST['Date_Target'][$i]."',                
                        '".$_POST['Weightage_Target'][$i]."',
                        '$statement',)";
            }

          $stmt = sqlsrv_query($conn, $sql);
          if($stmt === false)
          {
            die(print_r(sqlsrv_errors(), true));
          }
          else
          {
            echo " ";
          }
        }

        for($i = 0; $i < count($_POST['Measures']); $i++) {
            if(isset($arrMeasuresInsData[$i])) {
                continue;
            }
          $sql="INSERT INTO Appraisal_Objectives (Serial_Number,Objectives,Measures,Targets,Weightage,Row_Number,target_date,ID) 
                VALUES ('$formno',
                        '".$_POST['Objectives'][$i]."',
                        '".$_POST['Measures'][$i]."',
                        '".$_POST['Achievement'][$i]."',
                        '".$_POST['Weightage_Target'][$i]."',
                        '".$_POST['SNo'][$i]."',
                        '".$_POST['Date_Target'][$i]."',
                        '$statement')"; 
          $stmt = sqlsrv_query($conn, $sql);
          if($stmt === false)
          {
            die(print_r(sqlsrv_errors(), true));
          }
          else
          {
            echo " ";
          }       
       }

答案 2 :(得分:0)

我认为你错误地获得了$ _POST数组。您必须更改输入表单并接收输入,如下所示:

[C_Objectives] => Array
    (
        [Row_Number] => Array
            (
                [title]         =>      'xxx',
                [0]             =>      Array
                    (
                        [0]     =>      Array
                            (
                                [SNo]           =>  2
                                [Objectives]    =>  a1,
                                [Measures]      =>  a2,
                                [Achievement]   =>  a3,
                                [Date_Target]   =>  2016-09-09,
                                [Weightage_Target]  =>  25
                            ),
                            (
                                [SNo]           =>  3
                                [Objectives]    =>  a1,
                                [Measures]      =>  a2,
                                [Achievement]   =>  a3,
                                [Date_Target]   =>  2016-09-09,
                                [Weightage_Target]  =>  25
                            ),
                            (
                                [SNo]           =>  4
                                [Objectives]    =>  a1,
                                [Measures]      =>  a2,
                                [Achievement]   =>  a3,
                                [Date_Target]   =>  2016-09-09,
                                [Weightage_Target]  =>  25
                            ),
                        [SubTotals] =>  75
                    )   
            )
    },
    (
        [Row_Number] => Array
            (
                [title]         =>      'xxx',
                [0]             =>      Array
                    (
                        [0]     =>      Array
                            (
                                [SNo]           =>  6
                                [Objectives]    =>  a1,
                                [Measures]      =>  a2,
                                [Achievement]   =>  a3,
                                [Date_Target]   =>  2016-09-09,
                                [Weightage_Target]  =>  25
                            ),
                        [SubTotals] =>  25
                    )   
            )
    )

以上是您必须了解如何做到这一点的唯一示例。

因为知道哪个值属于哪一行是很困难的,所以可能将该值定义为第二行到第三行。

答案 3 :(得分:0)

使用当前代码时,至少会有两个 INSERT 语句,当$_POST['Measures']$_POST['C_Objectives']包含更多元素时,会有更多语句。

您可以使用一个语句插入多个记录,而不是使用 for 语句,使用 foreach ,这样您就不必在迭代器上进行簿记变量。然后将值存储在数组中,并使用implode()组合每个记录的值集。

检查哪些值插入到哪些列中 - 看起来在示例的第一个 for 循环中,您将$_POST['SNo'][$i]中的值插入ID字段...

$values = array();
foreach($_POST['C_Objectives'] as $index=>$value) {
    $rowValues = array();
    $rowValues[] = $_POST['SNo'][$index];   //Serial_Number
    array_push($rowValues,$formno,'||<==','==','==');   //, Objectives, Measures, Targets, subtotal
    $rowValues[] = $_POST['SubTotals'][$index]; //Corporate_Objective
    $rowValues[] = $value;  //Row_Number: $value == $_POST['C_Objectives'][$index];
    $values[] = "('".implode("', '",$rowValues )."')";
}

$fields = array('Objectives','Measures','Achievement','Weightage_Target','SNo','Date_Target');
foreach($_POST['Measures'] as $index=>$value) {
    $rowValues = array($formno);
    foreach($fields as $field) {
        $rowValues[] = $_POST[$field][$index];
    }
    $values[] = "('".implode("', '",$rowValues )."')";
}

$sql = "INSERT INTO Appraisal_Objectives (Serial_Number,Objectives,Measures,Targets,subtotal,Corporate_Objective,Row_Number,ID) VALUES ".implode(', ',$values);

$stmt = sqlsrv_query($conn, $sql);
if($stmt === false) {
    die(print_r(sqlsrv_errors(), true));
}
else {
    echo " ";
}

答案 4 :(得分:-1)

你打算怎么办?两个循环执行是不同的插入.....

解决方案: 1.第二次更新操作。 2.立即将数据整理到数据库中。