【问题标题】:transferring values within elements of $_POST to pre-existing array将 $_POST 元素中的值传输到预先存在的数组
【发布时间】:2015-01-16 15:43:57
【问题描述】:

我将以下关联数组存储在一个 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);
    }
}

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

但是,如果我在 renderform 之前立即运行 $fields$emptyArray 的 print_r,我会收到与存储在$fields 之前的操作

数组([A] => A [B] => B [C] => C [...] => ...)

我可以按我的意图使用 $_POST[$field]($_POST[$field] 中的$field 值被转移到值存储在 $fields) 中?如果是这样,这是一种好的做法吗?

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

【问题讨论】:

标签: php mysql arrays post mysqli


【解决方案1】:

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

$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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多