PHP Array inserting too many records in the database

后端 未结 2 1464
情深已故
情深已故 2021-01-29 10:18

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 shou

相关标签:
2条回答
  • 2021-01-29 10:46

    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.

    0 讨论(0)
  • Not only do you need to modify your iterating technique to be a single loop and use the index of the subarray being iterated, it is essential that you defend your query from injection attacks and breakages due to single quotes in submitted values.

    I've never used odbc_, but it seems similar to PDO's execution.

    Use a single prepared statement and execute it inside of your loop.

    $stmt = odbc_prepare($conn, "INSERT INTO MRF_Request (Qty, Unit, Description, Cost) VALUES (?, ?, ?, ?)");
    foreach ($_POST['Quantity'] as $index => $qty) {
        odbc_execute($stmt, [$qty, $_POST['Unit'][$index], $_POST['Description'][$index], $_POST['Cost'][$index]]);
    }
    

    Be warned, according to https://www.php.net/manual/en/function.odbc-execute.php

    Any parameters in parameter_array which start and end with single quotes will be taken as the name of a file to read and send to the database server as the data for the appropriate placeholder.

    For the above reason and for other reasons (like maintaining clean data), you should valid/sanitize values before allowing them to be save.

    One way to defend against unwanted file reading would be to call a replacement on any qualifying values like this:

    $value = preg_replace('~^('+)(.*)\1$~', '$2', $value);
    

    This would ensure that no value would both begin and end with a single quote. (Demo)

    • Description is the "loosest" input field, you should be rather ruthless about sanitizing it.

    • Unit looks like a value where declaring a whitelist of acceptable values would be ideal. Perhaps consider a <select> field in the UI -- either way validation should be done.

    • Quantity looks like an integer, so you might call upon ctype_digit() and or have minimum/maximum allowances.

    • Cost may be a float. Depending on your preferred format, there are several techniques for validating.

    0 讨论(0)
提交回复
热议问题