Ben Ben - 2 years ago 124
PHP Question

PDO / mySQL How to bind multiple values to store multiple rows

To store 6 invoce items from a website through a

form method="post"
, I use several input elements like this

<input name="item[]" value="6 hour service"/>
<input name="item[]" value="1 days travel"/>

Serverside I copy $_POST['Item'] to an array like this

item[]= $_POST['Item'];

Then I can access item[] and it looks like this

[item] => Array
[0] => 6 hour service
[1] => 1 days travel
[2] => ....

Then this SQL statement follows

try {
$obj = $this->dbcon->prepare('INSERT INTO invoice_item
( ID, item)

for ($i=0;$i<6;$i++) {

if (!empty($item[0][$i])) {
$obj->bindValue(':ID', $this->dbcon->lastInsertId(), PDO::PARAM_INT);
$obj->bindValue(':item', $item[0][$i], PDO::PARAM_STR);
$succ = $obj->execute();

catch(PDOException $e) {
echo "Error: " . $e->getMessage();

This works fine for a fix amount of items.

But what is the correct way to access $_POST, bind it and to store it when the amount of items are not known ?

Answer Source

Check if $i is less than the number of items rather than less than a fixed value.

        for ($i=0;$i<count($item[0]);$i++) {

        if (!empty($item[0][$i])) {

alternatively you could use foreach:

        foreach ($item[0] as $value) {

        if (!empty($value)) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download