ZF2 insert multiple lines

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

I tried something like this, but it does not 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 ​​into a two-column database ( id_agent, id_projet )

+6
source share
1 answer

There is no general way for multi-user in ZF2, but if you use mysql and do not plan to change other databases, I wrote a multiInsert function for myself:

$data - an array of arrays of key pairs, values.

 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); } } 
+4
source

Source: https://habr.com/ru/post/948147/


All Articles