[英]Problems connecting to db using Zend db as standalone
I am migrating from ZF1 Zend_db to ZF2. 我正在从ZF1 Zend_db迁移到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.
那是$ dbo没有select(),insert()方法等。我可以在ZF1 zend db中做到这一点。
Example of error message i received: 我收到的错误消息示例:
Fatal error: Call to undefined method Zend\\Db\\Adapter\\Adapter::select() in
致命错误:调用未定义的方法Zend \\ Db \\ Adapter \\ Adapter :: select()
You seem to think that ZF2 and ZF1 are (and should be) class-compatible. 您似乎认为ZF2和ZF1是(并且应该是)类兼容的。 The problem is, they're not - at least in regards to
Zend\\Db\\Adapter
. 问题是,它们不是-至少在
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. ZF2中的那个更为简洁:尽管它具有
query
方法,但其主要职责是抽象数据库连接本身。
I suppose what you're looking for is located in Zend\\Db\\Sql area. 我想您要查找的内容位于Zend \\ Db \\ Sql区域。 Assuming you have your DB connection in
$dbo
, you can create an Sql object based on it: 假设您在
$dbo
具有数据库连接,则可以基于它创建一个Sql对象:
use Zend\Db\Sql as Sql;
$sql = new Sql\Sql($dbo);
... then create another object (of Zend\\Db\\Sql\\Insert
class): ...然后创建另一个对象(
Zend\\Db\\Sql\\Insert
类的):
$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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.