dte66654 2015-01-16 15:43
浏览 49

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

I have the following associative array stored in a php file also containing a database connect statement.

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

Here I am calling it

include('dbconnection.php');

What I intended from this code is that the $field values within $_POST[$field] would be transferred over to values stored within $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]));
    }

These new $fields array values would then be transferred over to $emptyArray, where elements of the array containing 0, NULL, FALSE, or "" values would be filtered out.

    $emptyArray = array();

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

    $emptyArray = array_filter($emptyArray);

Finally, after checking if there were any elements stored in $emptyArray, an error message would be issued, along with a call to run function 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 contains the argument $fields, the first array in this chain, which is why I chose to use $emptyArray instead of $fields in order to conserve its structure.

However, if I run print_r of $fields and $emptyArray immediately before renderform, I receive arrays identical to keys and values stored in $fields prior to their manipulation

Array ( [A] => A [B] => B [C] => C [...] => ...)

Can I use $_POST[$field] in the way that I'm intending ($field values within $_POST[$field] being transferred over to values stored within $fields)? If so, is this good practice?

Thanks for reading, I'm happy to answer any questions.

  • 写回答

1条回答 默认 最新

  • duangan6797 2015-01-16 16:05
    关注

    You could do this in a single loop:

    $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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line