Home    Articles


Zend Framework 2 Insert into table example, with get last insert id


If you want to find a quick way to use ZF2 INSERT here it is:

// this->db; - db adapter used bellow
// $data is an array that uses keys as columns and values as column value
/* $data = array('column1'=>'value1',
$sql = new \Zend\Db\Sql\Sql($this->db); 
$insert = $sql->insert()->into('admin')->values($data); // set table and values
// echo $insert->getSqlString(); // for debug
$insertObj = $sql->prepareStatementForSqlObject($insert); // prepare for insert
$insertObj->execute(); // insert
echo $this->db->getDriver()->getLastGeneratedValue(); // get last insert id

As you can see, i added the line that returns last Insert Id for those who might need it.

Since there is no generic way to use insert in Zend Framework 2, this is what i found more close to Zend Framework 1.

To be onest, ZF1 is more like "beginner friendly".