Inserting HTML Form $_POST Array Into MySQL Using Implode

一曲冷凌霜 提交于 2020-02-02 13:03:00

问题


I have the following html submit form. This form is a PHP_SELF and stores the input data as an array in $_POST.

<html>
<body>
<form method="post" action="<?php echo htmlentities($PHP_SELF); ?>">
<fieldset>
<legend>Direct Bill Information:</legend>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" /> </br>
DB #: <input type="int" name="db_num[]" /> DB Amount: <input type="int" name="db_amnt[]" />
</fieldset>
<input type="submit" value="submit" name="submit" />
</form>
</body>
</html>

I have a MySQL table that has the fields 'db_num' and 'db_amnt', and I want to insert all the input data in the array into the table. I've looked around and 'implode' seems to be the best way, but after much research I still can't get it to work. The entire PHP executes and finishes without error, however, instead of displaying all 10 rows of both columns, it just displays 2 rows of the two columns with values = 0 for all entries. This is the code I'm using:

$sql2 = array();
foreach($_POST as key=>$value)
{
    if(key != 'submit')
    {   
        if($value != '')
        {   
            $sql2[] = '("'.mysql_real_escape_string($value['db_num']).'", "'.$value['db_amnt'].'")';
        }   
    }
}
mysql_query('INSERT INTO ' .$tablename_db. '(db_num, db_amnt) VALUES '.implode(',', $sql2)); 

I did a little debugging and echoed the $value in the foreach loop, and it turns out that it's only displaying three terms; 'Array', 'Array', and 'submit'. Further checks showed that the only way I can get the values from the submit form to show is if I do a foreach loop through $_POST[db_num] and $_POST[db_amnt] instead of just $_POST. I'm not really sure why it's doing this and how to fix it. This is my first code in PHP and I'm learning as I go. I really appreciate any help that I can get!


回答1:


try this

$db_num = $_POST['db_num'];
$db_amnt = $_POST['db_amnt'];

$items = array_combine($db_num,$db_amnt);

$pairs = array();

foreach($items as $key=>$value){
  $pairs[] = '('.intval($key).','.intval($value).')';
}

mysql_query('INSERT INTO ' .$tablename_db. '(db_num, db_amnt) VALUES '.implode(',',$pairs));



回答2:


Upon submit, your html form will be generating the following $_POST array (I'll fabricate some sample values).

$_POST = [
    'db_num' => ['1', '2',  '3',  '4',  '5',  '6', '7', '8', '9', '10'],
    'db_amnt' => ['100', '125', '150', '175', '200', '225', '250', '275', '300', '325']
];

In other words, $_POST['db_num'] will have $_POST['db_num'][0] holding 1 all the way through $_POST['db_num'][9] holding 10. Likewise, $_POST['db_amnt'][0] will hold 100, $_POST['db_amnt'][1] will hold 125, and so forth. Even if a user fails to fill in one of the fields, the empty field will still be submitted and the value will be a zero-width string (empty string).

You have done yourself a great service by structuring your form data to provide such a clean and instantly usable/traversable set of data.

There is no need to restructuring the incoming data (despite voodoo's suggestion to use array_combine()). If any extra effort is called for at all, you might want to validate the "paired" values from each row of the form. For instance, I assume that you will only want to store data if both db_num and db_amnt for a given row are non-empty -- so I'll build that check into my suggested snippet.

$conn = new mysqli($server, $user, $password, $database);
$stmt = $conn->prepare("INSERT INTO {$tablename_db} (db_num, db_amnt) VALUES (?,?)");
$stmt->bind_param("ii", $num, $amnt);  // name the two variables which will pass integer values where the ?'s are located
foreach ($_POST['db_num'] as $index => $num) {
    $amnt = $_POST['db_amnt'][$index];
    if (strlen($num) && strlen($amnt)) {
        $stmt->execute();  // only INSERT qualifying rows
    }
}

Note, that if your db_amnt values have decimal places (they are floating point numbers), then you can change the i in the bind_param() call to d. Some people prefer the simplest route of declaring all of the values as s (string), but I like to rein it in when dealing with predictable user input.

Here is a demonstration of the iterating technique.

If you have other validating checks to make, just add them to my if expression.

If you want enjoy individual success checking, you can write something immediately under execute() to reference the affected rows.

Re-using a prepared statement is one of two ways that this process should be done with mysqli. The other involves building one, all-encompassing INSERT query with all rows in it, but that involves a bit more preparation. These two mysqli techniques are injection safe, stable, and efficient.

Finally, some developers will say that you should be checking if each index actually does exist in the subarrays before trying to access them; other developers insist that it is not necessary to handle Notices that are generated by users which are deliberately hacking your html. I'll leave it to individual researchers to determine whether they wish to make isset() calls before and while iterating.



来源:https://stackoverflow.com/questions/11720981/inserting-html-form-post-array-into-mysql-using-implode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!