简体   繁体   中英

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.

According to CodeIgniter 4 documentation , you can do this inside your loop for each employee:

$data = [
    'title' => $title,
    'name'  => $name,
    'date'  => $date
];

$db->table('mytable')->insert($data); 

You can use array and implode function first make array of key_array, value_array and bind_array then use implode() and use in sql like following

public function add_employee($input)
{
    $key_array = array();
    $value_array = array();
    $bind_array = array();
    foreach ($input as $column => $value) {
        if ($value) {
            $bind_array[] = '?';
            $value_array[] = $value;
            $key_array[] = $column;
        }
    }

    $binds = implode(",",$bind_array);
    $keys = implode(",",$key_array);    
    $values = implode(",",$value_array);
    $sql = "INSERT INTO ol_employee ($keys) VALUES ($binds)";
    $this->db->query($sql,$values);
}

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.

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