0

I have my table named i_table with columns:

id   name    req_qty  req_date     rcv_qty   rec_date
1    metal   1        2014-03-04
2    spring  5        2014-03-04

in my html/php:

<form action="insert.php" method="post">
<?php $resource2=mysql_query("SELECT * FROM i_table",$con);
    while($result2=mysql_fetch_array($resource2))
        { 
?>
<table>
<tr>
<td>
<input type="text" name="id" value="<?php echo $result2['id'];?>"/>
</td>
</tr>

<tr>
<td>
<input type="text" name="name" value="<?php echo $result2['name'];?>"/>
</td>
</tr>

<tr>
<td>
<input type="text" name="rcv[]" value="" />
</td>
</tr>

<tr>
<td>
<input type="date" name="rcv_date[]" value="" />
</td>
</tr>

</table>


<?php };?>

</form>

how can I insert in multiple arrays from an input according to their unique ID from db? pls help me here... huhu

user3117337
  • 213
  • 1
  • 5
  • 17

1 Answers1

1

In your form, add the id as the key -

<form action="insert.php" method="post">
<?php $resource2=mysql_query("SELECT * FROM i_table",$con);
    while($result2=mysql_fetch_array($resource2))
        { 
?>
<table>
<tr>
<td>
<input type="text" name="id[<?php echo $result2['id'];?>]" value="<?php echo $result2['id'];?>"/>
</td>
</tr>

<tr>
<td>
<input type="text" name="name[<?php echo $result2['id'];?>]" value="<?php echo $result2['name'];?>"/>
</td>
</tr>

<tr>
<td>
<input type="text" name="rcv[<?php echo $result2['id'];?>]" value="" />
</td>
</tr>

<tr>
<td>
<input type="date" name="rcv_date[<?php echo $result2['id'];?>]" value="" />
</td>
</tr>

</table>

<?php };?>

</form>

Then on your insert.php where you post your form, get the id in your foreach -

<?php
 if(isset($_POST['id'])){
    foreach($_POST['id'] as $id=>$value){

    $sql = "UPDATE `i_table` SET `name` = '".$_POST['name'][$id]."', `rcv_qty` = '".$_POST['rcv'][$id]."', `rec_date` = '".$_POST['name'][$id]."' WHERE `id` = ".$id."";

    mysql_query($sql,$con);
    }
 }
?>

note the foreach() is just an example. You will want to sanitize your data before inserting/updating to prevent sql injection. see How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Sean
  • 12,443
  • 3
  • 29
  • 47
  • where do i get the variable $value? where did this came from? – user3117337 Mar 11 '14 at 16:54
  • `$value` is just user defined variable inside a `foreach()` loop (it could also be `$v`, `$x`, `$val`, etc). It might be helpful for you to read the php manual `foreach (array_expression as $key => $value)` - http://php.net/manual/en/control-structures.foreach.php. I did not use it in my example, but it had to be there so I could access the `$key`, or it would produce a syntax error. Typically you would access/use the `$value` value. – Sean Mar 11 '14 at 17:09