Reputation: 21
How can I use foreach
to insert multiple data in my database.
I have a drop-down menu from my form
that will be used to add and delete rows by js function. I would like to insert data from the new row (added in the form) into my database.
This is my form:
<form action="insert.php" method="POST">
<input type="button" value="Add Row" onClick="addRow('tableID')"/>
<input type="button" value="Delete Row"
onClick="deleteRow('tableID')"/>
<table class="table" bgcolor="#CCCCCC">
<thead>
<tr>
<td></td>
<td><center>Item Description</center></td>
<td><center>Price (RM)</center></td>
<td><center>Month</center></td>
<td><center>Amount (RM)</center></td>
</tr>
</thead>
<tbody id="tableID">
<tr>
<td><input type="checkbox" name="chk"></td>
<td>
<select name="item_description">
<option value="deposit">Deposit</option>
<option value="rental">Rental</option>
<option value="stamp">Stamp Duty</option>
<option value="process">Process Fee</option>
<option value="ap">AP</option>
</select>
</td>
<td><input id="price" name="price" type="text"></td>
<td><input id="month" name="qty" type="text"></td>
<td><input id="amount" name="amount" type="text"></td>
</tr>
</tbody>
</table>
</form>
This is my insert query:
<?php
//some connection code here
if(isset($_POST['submit']))
{
$item = array(
'item_description' => '',
'price' => '',
'qty' => '',
'amount' => '',
);
foreach ($item as $key => $value){
$value = $_POST[$key];
}
}
$last_insert_payment_id=mysql_insert_id();
$sql1="INSERT INTO payment_item (payment_id, payment_item_id, item_description, price, qty, amount)
VALUES
('$last_insert_payment_id','NULL','$_POST[item_description]','$_POST[price]','$_POST[qty]','$_POST[amount]')";
if (!mysql_query($sql1,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
Hope someone can help me to figure this out. Thank you.
Upvotes: 2
Views: 192
Reputation: 56905
So you mean when you click 'Add row' and enter extra rows of data and then click 'Submit', only the last row gets inserted into the database?
I'm guessing that when you click 'Add Row', the following HTML is added to your table (same as the row in your question)
<tr>
<td><input type="checkbox" name="chk"></td>
... and so on
In this case, your $_POST['price']
, $_POST['chk']
etc are probably getting overwritten for each row, because you now have multiple inputs with hane chk
.
Try setting your input id="chk[]"
instead of input id="chk"
, and then $_POST['chk']
will be an array, one for each row.
You could access each row via $_POST['chk'][i]
.
There are also the other recommendations in the comments about making your code safe to SQL injection, and the fact that $_POST[price]
(like you have in your SQL statement) is invalid syntax; you probably want $_POST['price']
. (Daedalus, Marc B, Los Frijoles).
Upvotes: 2