PHP:根据 ID 或行日期将多个输入字段保存在行中


PHP: Saving multiple input fields in rows based on ID or date of row

我不完全确定这个标题的描述性,但是:

在Wordpress中,我有一个自定义的数字数据表,该表被添加到每月(通过电子表格导入)。因此,我使用 $wpdb 来拉取该表的内容,该表作为 stdClass 对象数组返回:

Array
(
    [0] => stdClass Object
        (
            [id] => 553
            [assocID] => 1
            [title] => Afghanistan
            [weight_political] => 8.2
            [indicator_political] => 0.0
            [weight_security] => 9.5
            [indicator_security] => 0.0
            [weight_criminal] => 9.5
            [indicator_criminal] => 1.0
            [weight_governance] => 9.0
            [indicator_governance] => 0.0
            [overall_score] => 9.2
            [datamonth] => 2013-08-18
            [active] => 1
        )
    [1] => stdClass Object
        (
            [id] => 369
            [assocID] => 1
            [title] => Afghanistan
            [weight_political] => 8.4
            [indicator_political] => 0.0
            [weight_security] => 9.5
            [indicator_security] => 0.0
            [weight_criminal] => 9.3
            [indicator_criminal] => 1.0
            [weight_governance] => 9.0
            [indicator_governance] => 0.0
            [overall_score] => 9.2
            [datamonth] => 2013-07-05
            [active] => 1
        )
)

这很好,并且准确地给了我想要的东西,然后我可以将其作为一系列输入字段进行编辑(有关示例输出,请参阅我的 jsFiddle)。

但是,我无法理解的是(我很确定我只是在这里超级愚蠢并且错过了一些明显的东西)是将适当的数据保存适当的数据库行。

我考虑过将输入名称设置为数组(即 <input name="weight_security[]"... ),但它显然缺少参考。我希望将 2013 年 8 月的数据 (id 553) 保存到 2013 年 8 月行;我只是不知道在哪里或如何实现该引用。

在此示例中,只有 2 行,但一旦上线,可能会有多达 14 行,并将添加到每月,因此同时修改多行的能力是关键。

任何帮助将不胜感激。

回答我自己的问题:键在输入名称的多维数组中; 所以,而不是多个字段,如:

<input name="weight_political" value="8.2" />
<input name="indicator_political" value="0" />

我决定更上一层楼,将这些字段名称包装在一个名为 geodata 的数组中,并且至关重要的是,用数组键作为需要更新的行的 ID 作为开头,因此:

<input name="geodata[553][weight_political]" value="8.2" />
<input name="geodata[553][indicator_political]" value="0" />

然后,在解析发布的数据时,我可以遍历geodata数组以获取行 ID(作为键),然后将数据作为其中的关联数组:

<?php
if ($_POST["geodata"]) {
        foreach ($_POST["geodata"] as $rowID=>$valuesArray) {
            $queryArray = array();
            foreach ($valuesArray as $key=>$value) {
                $queryArray[] = $key . ' = '  . $value;
            }
            $queryString = implode(', ', $queryArray);
            $wpdb->query("UPDATE $table_name SET $queryString WHERE id = $rowID");
        }
    }
?>

也:

为了尽可能高效(因为初始的 9x14 网格将返回 126 个值进行更新,其中许多是不必要的),我编写了一个小的 jQuery 函数来检测输入字段何时更改;如果是这样,则其namedata[id][identifier] 更改为 geodata[id][identifier] - 这样,$_POST['geodata']只会发送需要更新的值, 而不是整个批次。jsFiddle下面,对于那些感兴趣的人。

http://jsfiddle.net/hkVTn/1/