0

This is my first attempt to post multiple records for a single table column and would need some help.

First, how can I post these records in an array?

<?php
  <form action="set_order.php" method="POST">
  <table>
    <tr>
  $query = mysql_query("SELECT * FROM table ORDER BY order");
  while ($result = mysql_fetch_assoc($query)) {
?>
      <td><?php echo $result['order']; ?></td> //show current order
      <td><input type="text" name="order[]" value="<?php echo $result['order']; ?>" /></td>  //input new order
      <td><input type="hidden" name="id[]" value="<?php echo $result['id']; ?>" /></td> //send related id
    </tr>
    <tr>
      <td colspan ="2"><input type="submit" value="save" />
    </tr>
  </table>
  </form>

Second question is how to insert array to table.

table

id | order
1  |  3
2  |  4
3  |  2
4  |  1

I found this: Post array from form to update mysql table

<?php
foreach ($_POST['id'] as $id) {
$order = $_POST['order']; // here is the problem
echo $id . ',' . $order . '<br />';
}
?>

But I can't get the result using ECHO.

I get:

1, Array
2, Array
3, Array
4, Array

If I can make that works, I think I can manage to update the table accordingly using FOREACH.

Community
  • 1
  • 1
Michael Eugene Yuen
  • 2,470
  • 2
  • 17
  • 19

2 Answers2

2

Both $_POST['id'] and $_POST['order'] are arrays, it's a good idea to iterate over id's but then you need to retrieve the corresponding element of $_POST['order'] at each iteration.

As both arrays are filled in simultaneously when the HTTP request comes to the server, the matching elements should share the same keys, so that should work:

<?php
foreach ($_POST['id'] as $key=>$id) {
    $order = $_POST['order'][$key];
    echo $id . ',' . $order . '<br />';
}
?>
rkz_io
  • 187
  • 10
0

In php, you can't directly print an array. So you must use a foreach loop to loop through the elements one by one and echo them:

foreach ($order as $orderElem) 
    echo $orderElem;

In your code you are already looping through the id array, but you have forgotten the order array. So you will have to use this piece of code inside your already existing foreach loop.

Joren
  • 3,068
  • 25
  • 44
  • Thanks. But how can I have two loops working together? Something like: foreach (($_POST['id'] as $id) AND ($_POST['order'] as $order)) { do something } – Michael Eugene Yuen Jun 30 '13 at 16:46
  • No, it would be more like foreach($list1 as elem1) { foreach($list2 as elem2) { do_something_with_elem1_and_elem2(); } } – Joren Jun 30 '13 at 17:23