Skip to content
Advertisement

How to loop multiple form input and assign into sql query in php?

public function add_employee($input)
{
    $key_array = null;
    $value_array = null;
    $bind_array = null;
    foreach ($input as $column => $value) {
        if ($value) {
            #$bind_array => ?, ?, ?;
            #$value_array => [$value1, $value2, $value3];
            #$key_array => column1, column2, column3;
        }
    }
    $sql = "INSERT INTO ol_employee ($key_array) VALUES ($bind_array)";
    $this->db->query($sql, $value_array);
}

Refer to comment in the function, how to achieve that output? the idea is, from the input POST i get which over 27 fields, i just want to fill in into the $sql query i prepared as you can see. I don’t think writing each table column manually is a good way.

im using Codeigniter 4 php framework + postgresql.

Advertisement

Answer

by the insight of Alex Granados, this is the query i use:

public function add_employee($input)
{
    foreach ($input as $column => $value) {
        if ($value) {
            $data[$column] = $value;
        }
    }

    $this->db->table('ol_employee')->insert($data);
}

this will eliminate null field and regardless how many field, still working good. as long the input name field from form is same as db column. Else, need to do some changes on that.

Thanks guys.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement