将 $_POST 元素中的值传输到预先存在的数组


transferring values within elements of $_POST to pre-existing array

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

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

我在这里称呼它

include('dbconnection.php');

我从这段代码中的意思是,$_POST[$field] 中的$field值将被转移到存储在$fields中的值。

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 或 " 值的数组元素将被过滤掉。

    $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$emptyArray print_r,则会收到与操作之前存储在$fields中的键和值相同的数组

数组 ( [A] => A [B] =>

B [C] => C [...] => ...)

我可以按照我想要的方式使用 $_POST[$field] 吗($field $_POST[$field] 以内的值转移到存储在 $fields 中的值)?如果是这样,这是好的做法吗?

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

您可以在单个循环中执行此操作:

$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