简体   繁体   English

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

[英]How to insert multiple dynamic rows into the database

I have a multiple row dynamic table that I created using php and jQuery. 我有一个使用php和jQuery创建的多行动态表。 Here's the link to view the table . 这是查看表格的链接

Everything is working fine except when I insert the data into the database, the serial numbers do not save sequentially. 一切工作正常,但当我将数据插入数据库时​​,序列号没有顺序保存。 My insert queries are as below: 我的插入查询如下:

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

The serial number is saved in the column Row_Number, using $_POST['SNo'][$i] . 序列号使用$_POST['SNo'][$i] SNo $_POST['SNo'][$i]保存在Row_Number列中。 Is it possible to save both of the dynamic rows using 1 insert query so that the serial numbers are saved sequentially? 是否可以使用1个插入查询保存两个动态行,以便顺序保存序列号?

This is the $_POST array result: 这是$_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
)

I've also tried making the column auto-increment, but yet doesn't save the data in the same order as it is entered in the front end. 我也尝试过使列自动递增,但是并没有按照在前端输入的相同顺序保存数据。

在此处输入图片说明

在此处输入图片说明

Your inserting has performance issue. 您插入的内容存在性能问题。 Please change your way for inserting to the database. 请更改插入数据库的方式。 You can do all of them in one query. 您可以在一个查询中完成所有这些操作。 Even if you have 20 loop for first "for" and 20 loop for 2nd "for". 即使第一个“ for”有20个循环,第二个“ for”有20个循环。

Answer to What you asked 回答你的要求

If you want to insert by $_POST['SNo'] order, change this line 如果要按$ _POST ['SNo']顺序插入,请更改此行

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

to the

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

If you need multiple insert at once, just do this: 如果您一次需要多个插入,只需执行以下操作:

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

This is What you MUST do 这是你必须做的

In your code, you did the same query in 6 queries. 在您的代码中,您在6个查询中执行了相同的查询。 It can even be more than 6 with more $_POST['Measures'] or $_POST['C_Objectives'] array length. $ _POST ['Measures']或$ _POST ['C_Objectives']数组的长度甚至可以大于6。 You need to Put them in one query and when you don't need to set the value, just set it to the column default value. 您需要将它们放在一个查询中,并且在不需要设置值时,只需将其设置为列默认值即可。 for example NULL 例如NULL

Something like this: 像这样:

//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";

In this example I just showed you how to do it. 在此示例中,我仅向您展示了如何进行。 Remember, you must check $v and prepare it by your column type. 请记住,必须检查$ v并按列类型进行准备。 check if $_POST[KEY] is set and it's array. 检查$_POST[KEY]是否已设置及其数组。 Don't insert to the database if $query is empty. 如果$query为空,请勿插入数据库。

Very Important about your codes 关于您的代码非常重要

If this is not your original code there is no problem but if it is, please change the way you are using $_POST inside your query. 如果这不是您的原始代码,那没有问题,但是如果是这样,请更改查询中使用$ _POST的方式。 It has very low security. 它的安全性非常低。 at least you need to validate them before using it. 至少您需要在使用前对其进行验证。

Yes you can able to insert in single insert query. 是的,您可以在单个插入查询中插入。

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

I think you are getting your $_POST array wrongly. 我认为您错误地获取了$ _POST数组。 You have to change the input form and recieve the input some thing like below: 您必须更改输入形式,并收到如下所示的输入:

[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
                    )   
            )
    )

Above is the only example rest you have to understand how to do that. 上面是剩下的唯一示例,您必须了解如何执行此操作。

As it would be difficlut to know which value belong to which row it might be possible that value defined as 2nd below to 3rd row. 因为很难知道哪个值属于哪一行,所以可能将该值定义为下面的第二行到第三行。

With the current code, there will be at least two INSERT statements, and more when $_POST['Measures'] or $_POST['C_Objectives'] contain a larger number of elements. 在当前代码中,将至少有两个INSERT语句,而当$_POST['Measures']$_POST['C_Objectives']包含更多元素时,则更多。

You can insert multiple records with one statement, and instead of using a for statement, use a foreach so you don't have to do the bookkeeping on the iterator variable. 您可以使用一个语句插入多个记录,而不必使用for语句,而使用foreach,这样您就不必对iterator变量进行簿记。 Then store values in arrays and use implode() to combine the sets of values for each record. 然后将值存储在数组中,并使用implode()组合每个记录的值集。

Check which values are being inserted into which columns - it appears that in the first for loop of your example, you are inserting the value from $_POST['SNo'][$i] into the ID field... 检查将哪些值插入到哪些列中-看来在示例的第一个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 " ";
}

what are you going to do? 你会怎样做? Two loop execution is different insertion ..... 两个循环执行是不同的插入.....

Solution: 1. The second update operation. 解决方案:1.第二次更新操作。 2. organize the data into the database at once. 2.立即将数据组织到数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM