将$ _POST元素内的值传递给预先存在的数组

时间:2015-01-16 15:43:57

标签: php mysql arrays post mysqli

我将以下关联数组存储在一个也包含数据库连接语句的php文件中。

$fields = array(
    "A" => "A",
    "B" => "B",
    "C" => "C",
    ...
);

我在这称呼

include('dbconnection.php');

我在此代码中的意图是 $ _ POST [$ field] 中的 $ field 值将转移到 $ fields <中存储的值/ strong>即可。

if (isset($_POST['submit'])){

    //iterating through fields array
    foreach($fields as $column => $field){

        //cleaning and storing user input in fields array 
        $field = mysqli_real_escape_string($cxn , htmlspecialchars($_POST[$field]));
    }

然后将这些新的 $ fields 数组值转移到 $ emptyArray ,其中数组的元素包含0,NULL,FALSE或&#34;& #34;价值将被过滤掉。

    $emptyArray = array();

    $emptyArray = array_merge ($emptyArray, array_values($fields));

    $emptyArray = array_filter($emptyArray);

最后,在检查 $ emptyArray 中是否存在任何元素后,将发出错误消息,同时调用运行函数 renderform

    if (empty($emptyArray)){    
        $error = 'You have reached this message because you did not specify a field to update';
        renderForm($id, $fields, $error);
    }
}

函数 renderform 包含参数 $ fields ,这是该链中的第一个数组,这就是为什么我选择使用 $ emptyArray 而不是 $ fields 以节省其结构。

但是,如果我在渲染表格之前立即运行 $ fields 的print_r和 $ emptyArray ,我会收到与存储的键和值相同的数组在操作之前 $ fields

  

数组([A] =&gt; A [B] =&gt; B [C] =&gt; C [...] =&gt; ...)

我可以按照我想要的方式使用$ _POST [$ field]( $ _ POST [$ field] 中的 $ field 值存储在 $ fields 中的值?)?如果是这样,这是一个好习惯吗?

感谢阅读, 我很乐意回答任何问题。

1 个答案:

答案 0 :(得分:0)

你可以在一个循环中完成这个:

$fields = array(
    "A" => "A",
    "B" => "B",
    "C" => "C",
);
$post=[];
foreach($fields as $key => $val){
    if(!isset($_POST[$key]) || !$_POST[$key]){
        die("data for $key is incorrect or missing");
    }
    $post[$key] = mysqli_real_escape_string($cxn , htmlspecialchars($_POST[$key]));
}
//all is fine, use $post array for whatever you need it for