Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ZF2 insert multiple rows

I'd like to know if there is a way to insert multiple row in ZF2 using only one $sql object (and not using the query(SQL COMMAND) method).

I tried something like this, but it doesn't work:

public function setAgentProjectLink( $IDProject , $IDsAgents )
{
    $values = array () ;
    foreach ( $IDsAgents as $IDAgent):
    {
        $values[] = array ( 'id_agent' => $IDAgent , 'id_projet' => $IDProject) ;
    } endforeach ;

    $sql = new Sql( $this->tableGateway->adapter ) ;
    $insert = $sql->insert() ;

    $insert -> into ( $this->tableGateway->getTable() )
            -> values ( $values ) ;

    $statement = $sql->prepareStatementForSqlObject($insert);
    $result = $statement->execute();
}

Trying to insert values in a database with two columns (id_agent, id_projet)

like image 876
aramir Avatar asked Jun 26 '13 14:06

aramir


1 Answers

there is no generic way for multyinsert in ZF2 BUT if you are using mysql and not planning to change to other databases, i have written a multiInsert function for myself:

$data is an array of arrays of key,value pairs.

protected function multiInsert($table, array $data)
    {
        if (count($data)) {
            $columns = (array)current($data);
            $columns = array_keys($columns);
            $columnsCount = count($columns);
            $platform = $this->db->platform;
            array_filter($columns, function ($index, &$item) use ($platform) {
                $item = $platform->quoteIdentifier($item);
            });
            $columns = "(" . implode(',', $columns) . ")";

            $placeholder = array_fill(0, $columnsCount, '?');
            $placeholder = "(" . implode(',', $placeholder) . ")";
            $placeholder = implode(',', array_fill(0, count($data), $placeholder));

            $values = array();
            foreach ($data as $row) {
                foreach ($row as $key => $value) {
                    $values[] = $value;
                }
            }


            $table = $this->db->platform->quoteIdentifier($table);
            $q = "INSERT INTO $table $columns VALUES $placeholder";
            $this->db->query($q)->execute($values);
        }
    }
like image 104
Exlord Avatar answered Oct 24 '22 05:10

Exlord