如何使用foreach创建数组并稍后更新数据库

时间:2013-08-10 16:38:17

标签: php arrays

我有一个动态表单,根据我数据库中保存的信息填写问卷评级量表。每个评级由“选择”和“定义”组成。比例可以包含任何数量或等级。以下是5评级量表的示例:

Strongly Agree = I strongly agree with this statement.
Agree = I agree with this statement.
Neither Agree nor Disagree = I neither agree nor disagree with this statement.
Disagree = I disagree with this statement.
Strongly Disagree = I strongly disagree with this statement.

填充表单后,用户可以编辑任何选择或定义。我的表格填充就好了,但我无法弄清楚如何正确填充POST数据到一个数组,如果用户提交的改变或使用该数组在我的数据库编辑信息。

这是我的PHP:

if(isset($_POST['submit'])){
    $fields = "";
    $values = "";

    foreach($_POST as $key => $value) {
        $fields = mysql_real_escape_string($key);
        $values = mysql_real_escape_string($value);
        $entry .= "[". $fields . "=" . $values . "]";

        //Here is the start of the query that I'm building
        //$query = mysql_query("UPDATE `pd_selections` SET `pd_selection` = '  ', `pd_definition` = '  ' WHERE `pd_selection_id` = '$pd_selection_id' ") or die(mysql_error());

    }
}

如果我回应“entry”变量,这就是我收到的内容:

[selection_for_1 =强烈同意] [definition_for_1 = I强烈同意本声明。] [selection_for_2 =同意] [definition_for_2 =我同意此语句。]

如何从每个评级的数组中提取选择和定义?

如何用于更新数据库?

我是否走在正确的轨道上......哈哈!?

非常感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

出于安全考虑,您应该保留一个您可以接受的密钥列表,以防止用户修改密钥,这样可以防止人们向表单添加无效数据以及保留您可能不需要的字段。

创建一个数组以供选择另一个用于定义,并在检查有效字段时使用它来存储键/值:

$accept = array('selection_for_1', 'definition_for_1',
                'selection_for_2', 'definition_for_2');
$selection = array();
$definition = array();
foreach ($_POST as $key => $value)
{
    // if not valid go to next field/value
    if(!in_array($key, $accept))
        continue;

    // if start with selection save to $selection array
    // otherwise to definition array
    if (strpos($key, 'selection') !== false)
    {
        $selection[] = mysql_real_escape_string($value);
    }
    else
    {
        $definition[] = mysql_real_escape_string($value);
    }
}

// count one of the array to select the paired fields 
// and insert or update into database
$total = count($definition);
for ($i=0; $i < $total; $i++)
{
    // Update query for the paired selection and definition
    $query = mysql_query("UPDATE pd_selections 
                             SET pd_selection = '{$selection[$i]}', 
                                 pd_definition = '{$definition[$i]}'
                           WHERE pd_selection_id = '{$pd_selection_id}'")
    or echo("Could not insert or update selection '{$selection[$i]}', definition '{$definition[$i]}', failed with error:", mysql_error());
}

Live DEMO.