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
)
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With