0

I am finding the following error: "Warning: htmlspecialchars() expects parameter 1 to be string, array given..."

This happens in the following piece of code and only when I added input fields to the form whose name was an array (so I could repeat the input multiple times). The line the error refers to is ($v=htmlspecialchars($value);)

if ($len > 2) {
    $values=array();
    $possible=array('orderId','source','date', 'clientPrice','firstName','lastName','email','address','city','zip');
    $i=1;
    $query2 = "UPDATE orders SET ";
    foreach ($_POST as $key => $value) {
        $k=htmlspecialchars($key);
        $v=htmlspecialchars($value);
        if(in_array($k, $possible)) {
            $query2 .= $k." = ?";
            $values[]=$v;  //append values to an array for later use
            if($i < ($len-2)) $query2 .= ', ';
            $i++;
        }
    }
}

Any idea of how to solve this and the reason for the error?

4

3 回答 3

1

您在第一段中回答了您自己的问题。您将数组作为值传递,因此$value将成为您分配数组名称的各种输入的数组。

foreach($_POST as $key => $value)
{
    if ( ! is_array($value))
    {
        // Manage values that aren't arrays
    }
}

迭代$_POST并不是一个好习惯。您最好将字段的实际名称分配给它们自己的变量,或者使用您需要的确切数据创建自己的数组。

于 2013-09-16T19:54:21.917 回答
0

不要处理所有 _POST 值。仅检查您需要的内容。尝试此代码以获取不同的方法,更正确。

foreach ($possible as $_possib) {
    if (!isset($_POST[$_possib])) continue;
    $query1 .= $_possib." = ?";
    $values[] = htmlspecialchars($_POST[$_possib]); // should be mysql_real_escape?
    if($i < ($len-2)) $query2 .= ', ';
    $i++;
}

顺便说一下,请考虑 htmlspecialchars,因为它仅用于正确显示 html 格式。您似乎会将这些值提交到数据库,因此请使用相关的转义函数。

于 2013-09-16T19:55:30.100 回答
0

如错误所述,至少您的 $_POST 值之一似乎是一个数组。

尝试将您的 htmlspecialchars() 调用包装在 array_walk_recursive 中。我还添加了一个 if(is_array()) 检查,以便仅在需要时应用它。

if(is_array($value)) array_walk_recursive(htmlspecialchars($value));

或者,您可能希望 var_dump($_POST) 查看哪些输入字段显示为数组,如果这是不受欢迎的行为,可能会相应地调整您的表单。

于 2013-09-16T19:55:48.327 回答