Reputation: 1547
I am trying to save data from a multidimensional array in my POST data to my database but I don't know how to do it with more than 2 "array[][]"
this is what I have now.
index.php
$i = 0;
foreach($row as $new){
<input name='data[<?php echo $i?>][price]' id='price' type="number" size="4">
<input name='data[<?php echo $i?>][name]' id='name' type="number" size="4">
<input name='data[<?php echo $i?>][field]' id='field' type="number" size="4">
<input name='data[<?php echo $i?>][other]' id='other' type="number" size="4">
$i++;
}
form_submit.php
foreach ($_POST['data'] as $val) {
$price = $val['price'];
$name= $val['name'];
$field= $val['field'];
$other= $val['other'];
//query that saves into database works
}
but I want to send something like this
index.php
<?php
$i = 0;
foreach($row as $new){
?>
<input name='data[<?php echo $i?>][price][<?php $new->id; ?>]' id='price' type="number" size="4">
<input name='data[<?php echo $i?>][name][<?php $new->id; ?>]' id='name' type="number" size="4">
<input name='data[<?php echo $i?>][field][<?php $new->id; ?>]' id='field' type="number" size="4">
<input name='data[<?php echo $i?>][other][<?php $new->id; ?>]' id='other' type="number" size="4">
<?php
$i++;
}
?>
in form_submit how do I get the $new->id so that I can update (price, name, field, and other) in my table where $new->id is equal to the id in my database.
form_submit.php
foreach ($_POST['data'] as $val) {
$price = $val['price'];
$name= $val['name'];
$field= $val['field'];
$other= $val['other'];
//stuck here at form_submit
}
Upvotes: 0
Views: 36
Reputation: 54796
Modify your form and use id
instead of $i
:
<?php
foreach($row as $new){?>
<input name='data[<?php $new->id; ?>][price]' id='price' type="number" size="4">
<input name='data[<?php $new->id; ?>][name]' id='name' type="number" size="4">
<input name='data[<?php $new->id; ?>][field]' id='field' type="number" size="4">
<input name='data[<?php $new->id; ?>][other]' id='other' type="number" size="4">
<?php
}
After that you can iterate:
foreach ($_POST['data'] as $id => $val) {
$price = $val['price'];
$name= $val['name'];
$field= $val['field'];
$other= $val['other'];
// update query will look like:
UPDATE table SET field = $price, .... WHERE id = $id
}
Upvotes: 3