新手:如何在zend框架上正确设置数据库连接?

时间:2010-12-06 03:53:00

标签: php zend-framework pdo database-connection zend-db

我对OOP和Zend很新。到目前为止,我正在尝试建立数据库连接。我在application.ini文件中有这个:

resources.db.adapter = "PDO_MYSQL"
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = ""
resources.db.params.dbname = "dbtest"
resources.db.isDefaultTableAdapter = true

据说我可以通过以下方式访问数据库适配器:

$db = Zend_Db_Table::getDefaultAdapter();

问题是大多数指南假设你自动知道放在哪里,但老实说我不知道​​。我到目前为止所做的是在我的Index.php模型中我有一个方法:

public function getPosts()
{
 $db = Zend_Db_Table::getDefaultAdapter();
 $sql = "SELECT * FROM posts";
 $result = $db->fetchAll($sql);
 return $result;
}

使用那一个查询就可以了,但如果我想创建更多的方法来保存我的其他查询,每次我必须调用$ db = Zend_Db_Table :: getDefaultAdapter()所以我确定我不是以有效的方式做到这一点。我已经尝试将它放在各种__construct()和init()方法中,但它不起作用。我在哪里添加代码而不必每次都调用它?感谢。

1 个答案:

答案 0 :(得分:3)

运行查询的一种简单方法是为每个扩展Zend_Db_Table_Abstract的表创建一个类,它将为您提供一些方便的方法来帮助您从数据库中获取内容。

使用此方法时,您可以通过

调用表格内容
$postsTable = new Model_Db_Tables_Posts() // Assuming you put your class post in the folders models/db/tables/
$posts = $postsTable->fetchAll();

对于更具体的帖子,您也可以使用

按ID获取
$singlePost = $postsTable->find(1); // Assuming the id of the post you want is 1

然后创建新条目,您可以使用

$data = array('title' => 'Some title', 'content' => 'Some Content') // where the key is the table field and the value is the value you want to insert
$newId = $postsTable->insert($data);

并进行更新

$data = array('title' => 'Some title', 'content' => 'Some Content')
$db = $postsTable->getAdapter();
$where = $db->quoteInto('id = ?', $id); // quoteInto is used to escape unwanted chars in your query, not really usefull for integers, but still a good habit to have
$postsTable->update($data, $where);

希望这对您有所帮助,您可以在http://framework.zend.com/manual/fr/zend.db.table.htmlhttp://framework.zend.com/manual/fr/zend.db.table.row.html

的官方ZF文档中找到更多信息