如何在php

时间:2016-11-04 20:02:03

标签: php mysql arrays

我正在尝试将数据从我的POST数据中的多维数组保存到我的数据库中,但我不知道如何使用超过2&#34; array [] []&#34; < / p>

这就是我现在所拥有的。

的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 
}

但我想发送类似的东西

的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++;
}
?>

在form_submit中如何获取$ new-&gt; id以便我可以在我的表中更新(价格,名称,字段和其他)$ new-&gt; id等于我的数据库中的id。

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
}

1 个答案:

答案 0 :(得分:3)

修改表单并使用id代替$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
}

之后你可以迭代:

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
}