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
asked Mar 11, 2014 at 15:11
user3117337
2231 gold badge6 silver badges17 bronze badges
1 Answer 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?
answered Mar 11, 2014 at 15:47
Sean
12.4k3 gold badges31 silver badges49 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
user3117337
where do i get the variable $value? where did this came from?
Sean
$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) - 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.default
idas the key ->name="id[<?php echo $result2['id'];?>]",name="name[<?php echo $result2['id'];?>]",name="rcv[<?php echo $result2['id'];?>]",name="rcv_date[<?php echo $result2['id'];?>]". Then on post, usingforeach()you can get the keyid.