4

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
  • What is the issue you are getting? Commented Mar 7, 2013 at 5:49

2 Answers 2

12

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);
Sign up to request clarification or add additional context in comments.

3 Comments

getSqlStringForSqlObject() is deprecated in 2.4
buildSqlString() should handle the same in this case.
How to get the insert ID?
4

My proposition using TableGateway:

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

2 Comments

Fatal error: Interface 'Zend\EventManager\EventsCapableInterface' not found .. seems this require another module?
I have this way only, but I am surprised it is making two entries why so ? $otherTable = new Zend\Db\TableGateway\TableGateway('demo', \Config\Config::getAdapter()); $otherTable->insert(['name' => 500]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.