zf2 insert using $db->insert($table, $data); style

2019-05-03 12:24发布

问题:

Hello is there any way to insert data in a db table using the zf1 style on zf2?

$db->insert('tablename', $data);

where $data is an associative array contains (columns, values)

thanks

回答1:

To make an insert in zf2:

    use Zend\Db\Sql\Sql;

    $sql = new Sql($this->dbAdapter);
    $insert = $sql->insert('table');
    $newData = array(
    'col1'=> 'val1',
    'col2'=> 'val2',
    'col3'=> 'val3'
    );
    $insert->values($newData);
    $selectString = $sql->getSqlStringForSqlObject($insert);
    $results = $this->dbAdapter->query($selectString, Adapter::QUERY_MODE_EXECUTE);


回答2:

My proposition using TableGateway:

    $adapter = $this->tableGateway->getAdapter();
    $otherTable = new Zend\Db\TableGateway\TableGateway('table_name', $adapter);
    $otherTable->insert($data));