简体   繁体   中英

How to assign array multiple values with isset input on form submition in php

I am trying get a form submitted values in array after isset() but it store only last isset() value in array. What is the right way to get all not null values in array to pass to insert function.

$table = 'booking';
if(isset($_POST['tourID'])){
    $data = array('tour_fk' => $this->input->post('tourID'));
}
if(isset($_POST['bookingNumber'])){
    $data = array('booking_number' => $this->input->post('bookingNumber'));
}
$query = $this->dashboard_model->insert($table, $data);

The right way is to add new keys to $data instead of reassigning it:

if (isset($_POST['tourID'])){
    $data['tour_fk'] = $this->input->post('tourID');
}
if (isset($_POST['bookingNumber'])){
    $data['booking_number'] = $this->input->post('bookingNumber');
}

You can achieve like this.Make a array of all not null keys with values.Not need to write isset() for each posted items.Just make use of foreach loop.And achieve your result.

$table = 'booking';
foreach($_POST as $key=>$value) {
    if(isset($_POST[$key])) {
        $data[$key]=$this->input->post($key);
    }
}
//print_r($data);

Here is an example for you..

$array = array('tour_fk'=>1,'booking_number'=>11,'empty_field'=>NULL);
foreach($array as $key=>$value) {
    if(isset($array[$key])) {
        $data[$key]=$value;
    }
}
    print_r($data);

Output:

Array ( [tour_fk] => 1 [booking_number] => 11 )//without null values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM