php在数据库中一次将数据保存为两行?

时间:2015-02-13 11:04:50

标签: php arrays sorting multidimensional-array

我有一个这样的表格

<form class="product-data" action="">
    <table>
        <tr class="data-row">
            <td> 
                <input type="number" name="finance[a][source_unit]" >
            </td>
            <td >
                <input type="number" name="finance[a][target_unit]">
            </td>
            <td>
                <input type="number" name="finance[a][client_price]">
            </td>
            <td>
                <input type="number" name="finance[a][client_salary]" >
            </td>
    </tr>
    <tr class="data-row">
        <td>
            <input type="number" name="finance[b][source_unit]" >
        </td>
        <td >
            <input type="number" name="finance[b][target_unit]">
        </td>
        <td>
            <input type="number" name="finance[b][client_price]">
        </td>
        <td>
            <input type="number" name="finance[b][client_salary]" >
        </td>
    </tr>
    </table>
</form>

在这里你可以看到我有两行。一个用于a,另一个用于b。现在我想用两行将它们保存在数据库中。一个用于a,另一个用于b同时用于b。当我在做print_r(财务)。使用此代码

$finances = $_POST['finance'];
    print_r($finances);

它向我展示了一个像这样的数组

Array
(
    [a] => Array
        (
            [source_unit] => 3213
            [target_unit] => 657654322343
            [client_price] => 5435.00
            [client_salary] => 897.00
        )

    [a] => Array
        (
            [source_units] => 67656565
            [target_units] => 43243
            [client_price] => 23432.00
            [client_salary] => 6546.00
        )

)

现在有人可以告诉我如何在每一行中保存它们。我的数据库表是这样的,数据应该像这样保存

Id, product_type, source_unit, target_unit, client_price, lient_salary
1       A            3213        657654322343     5435           897
2       B            67656565     43243           23432           6546

2 个答案:

答案 0 :(得分:0)

我有两个解决方案。只有针对此场景量身定制:

$f = $_POST['finance'];

// insert first row
$query = "INSERT INTO `table` VALUES (NULL, 'A', {$f['a']['source_unit']}, {$f['a']['target_units']}, {$f['a']['client_price']}, {$f['a']['client_salary']})";
mysql_query($query);

// insert second row
$query = "INSERT INTO `table` VALUES (NULL, 'B', {$f['b']['source_unit']}, {$f['b']['target_units']}, {$f['b']['client_price']}, {$f['b']['client_salary']})";
mysql_query($query);

或者如果你有更多的通用(多行):

$f = $_POST['finance'];

foreach($f as $key => $item) {
    // assign key of the letter as value to insert
    $letter = strtoupper($key);

    // insert a row
    $query = "INSERT INTO `table` VALUES (NULL, '{$letter}', {$item['source_unit']}, {$item['target_units']}, {$item['client_price']}, {$item['client_salary']})";
    mysql_query($query);
}

答案 1 :(得分:0)

循环遍历您的数组并相应地插入或更新。

    foreach($finances as $key => $data)
    {
    //based on the $key if value exists in database update else insert
    echo $key.'<br />';
    echo $data['source_unit'].'<br />';
    echo $data['target_unit'].'<br />';
    echo '<hr />';
    }