簡體   English   中英

新手:如何在zend框架上正確設置數據庫連接?

[英]Novice: How to properly set up db connection on zend framework?

我對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()方法中,但是它不起作用。 我將在哪里添加代碼而不必每次都調用它? 謝謝。

運行查詢的一種簡單方法是為每個擴展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通過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);

希望對您有所幫助,您可以在官方ZF文檔中找到更多信息, 網址http://framework.zend.com/manual/fr/zend.db.table.htmlhttp://framework.zend.com/ manual / fr / zend.db.table.row.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM