rodrunner rodrunner - 19 days ago 8
MySQL Question

PHP: passing table row as hidden element in a form

I'm trying to pass the result of a SELECT query as a hidden input element in a form. Actually, I'm creating a form for every row in the result.

I know that is possible passing a hidden array in a form, so I assume it should also work passing a row of a table.

This is a snippet of the code that handles it:

$res = $conn->query($query);
while($row = $res->fetch()) {

echo '<form action="action.php" method="post">';

foreach ($row as $element) {
echo '<input type="hidden" name="row[]" value="'.$element.'">';
}

echo '<input type="submit" name="delete" value="Delete">';
echo "</form>";
}


Now, the action.php script just prints the received row:

<?php
echo "<pre>"; print_r($_POST['row']); echo "</pre>";
?>


The result of the query in mysql is

+--------+-------------+-----------+----------+------------+
| numero | id_producto | id_tienda | cantidad | f_pedido |
+--------+-------------+-----------+----------+------------+
| 7 | IXUS115HSAZ | 3 | 2 | 2015-10-01 |
+--------+-------------+-----------+----------+------------+
1 row in set (0.01 sec)


But the print_r of the row in action.php doubles every field:

Array
(
[0] => 7
[1] => 7
[2] => IXUS115HSAZ
[3] => IXUS115HSAZ
[4] => 3
[5] => 3
[6] => 2
[7] => 2
[8] => 2015-10-01
[9] => 2015-10-01
)


My mistake must be somehow obvious, but I can't find where it is.

Answer

You obviously use PDO

And as you can see from a manual - PDO fetch method takes as a first optional parameter a fetch_style.

And by default it is PDO::FETCH_BOTH which

returns an array indexed by both column name and 0-indexed column number as returned in your result set

So, you need to pass an argument to fetch either PDO::FETCH_ASSOC or PDO::FETCH_NUM:

while($row = $res->fetch(PDO::FETCH_ASSOC)) {

    // ... 

    // use `$field_name` to use  database field name
    foreach ($row as $field_name => $element) {
        echo '<input type="hidden" name="row[' . $field_name . ']" value="'.$element.'">';
    }

    // ...
}
Comments