PHP Array inserting too many records in the database

后端 未结 2 1486
情深已故
情深已故 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

    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

    提交评论

提交回复
热议问题