如何使用foreach创建数组,然后更新数据库


How to use foreach to create an array and later update a database

我有一个动态表单,它根据数据库中保存的信息填充问卷评分表。每个评级由一个"选择"和一个"定义"组成。量表可以由任何数字或等级组成。以下是一个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=我强烈同意这一说法。][selection''ufor_2=同意][definition _for_2=我同意这一声明。]

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

这是如何用来更新数据库的?

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

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

为了安全起见,您应该保留一个您可以接受的密钥列表,以防止用户修改它,这将防止人们向您的表单添加无效数据,并排除您可能不想要的字段。

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

$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());
}

现场演示