1

I am migrating from ZF1 Zend_db to ZF2. I have problems connecting to the db and making a simple query. Appreciate if someone can guide me along. Below is my code.

This is how i connect to db

use Zend\Db\Adapter\Adapter;
$dbo = new Zend\Db\Adapter\Adapter(array(
    'driver'   => 'pdo_mysql',
    'database' => DB_PREFIX.DB_NAME,
    'username' => DB_USER,
    'password' => DB_PW
));
Zend_Registry::set('db', $dbo);

This isan example how i use it.

$this->dbo = Zend_Registry::get('db');

function createData($message,$tags,$userid,$imgsrc){
    $data= array(
                      'message' => $message,
                      'tags' => $tags,
                      'imgsrc' => $imgsrc,
                      'createdtimestamp'=>new Zend_Db_Expr('NOW()'),
                      'userid' => $userid);   
    $this->dbo->insert('mydata', $data);
    return $this->dbo->lastInsertId();
}

I have an error. That is $dbo does not have select(),insert() methods etc. I could did it in ZF1 zend db.

Example of error message i received:

Fatal error: Call to undefined method Zend\Db\Adapter\Adapter::select() in

1

1 Answer 1

1

You seem to think that ZF2 and ZF1 are (and should be) class-compatible. The problem is, they're not - at least in regards to Zend\Db\Adapter. That one in ZF2 is much more concise: while it has query method, its main responsibility is abstracting the DB connection itself.

I suppose what you're looking for is located in Zend\Db\Sql area. Assuming you have your DB connection in $dbo, you can create an Sql object based on it:

use Zend\Db\Sql as Sql;
$sql = new Sql\Sql($dbo);

... then create another object (of Zend\Db\Sql\Insert class):

$insert = $sql->insert('mydata');
$insert->values([
   'message' => $message,
   'tags' => $tags,
   'imgsrc' => $imgsrc,
   'createdtimestamp'=>new Sql\Expression('NOW()'),
   'userid' => $userid
]);

... then use this object in query:

$insertString = $sql->getSqlStringForSqlObject($insert);
$results = $dbo->query($insertString, Adapter::QUERY_MODE_EXECUTE);
Sign up to request clarification or add additional context in comments.

Comments

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.