dsf6778 2015-12-25 15:52
浏览 49
已采纳

PHP数组在数据库中插入太多记录

If i enter only 1 record. It saves only 1 record in the database which is fine. But if i put two records of the same fields. It saves multiple records in the database which should only be two. What did i do wrong?

    <td>1.<input name='Description[]' type='text' required></td>

    <td><input type='text' name='Unit[]' placeholder='eg. reams,pcs,box' required></td>

    <td><input type='number' name='Quantity[]'  min='1' required></td>

    <td><input type='number' name='Cost[]' min='1' required></td>

    </tr>

I have a script that can add those fields again.

Here is the code:

foreach ($_POST["Description"] as $Description )
    {
        foreach ($_POST["Unit"] as $Unit)
        {
            foreach ($_POST["Quantity"] as $Quantity)
            {
                foreach ($_POST["Cost"] as $Cost)
                {
    $array = array($Description,$Unit,$Quantity,$Cost);
    odbc_exec($conn, "INSERT INTO MRF_Request (Qty,Unit,Description,Cost) VALUES 
    ('$Quantity' , '$Unit'  , '$Description' , '$Cost')");
                }
            }
        }
    }
  • 写回答

1条回答 默认 最新

  • doujishan2247 2015-12-25 16:04
    关注

    You can loop over only one field and use index for others to get appropriate data:

    foreach ($_POST["Description"] as $index => $val )
    {
        $Description = $_POST['Description'][$index];
        $Unit        = $_POST['Unit'][$index];
        $Quantity    = $_POST['Quantity'][$index];
        $Cost        = $_POST['Cost'][$index];
    
        $array = array($Description, $Unit, $Quantity, $Cost);
    
        $query = "
            INSERT INTO MRF_Request (Qty, Unit, Description, Cost) 
            VALUES ('$Quantity', '$Unit', '$Description', '$Cost')
        ";
    
        odbc_exec($conn, $query);
    }
    

    You should also think about sanitizing your $_POST data, to make the system secure and reliable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?