0
votes

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
Couldn't you just use array_map() - Jay Blanchard

1 Answers

0
votes

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