首先需要打开Pdo扩展。
在Windows目录下找到php.ini文件。打开extension=php_pdo_mysql.dll。
extension=php_pdo.dll
;extension=php_pdo_firebird.dll
;extension=php_pdo_mssql.dll
extension=php_pdo_mysql.dll
;extension=php_pdo_oci.dll
......
新建ZF工程如下图所示:
测试代码如下:
1.<?php 2. 3./** 4. * IndexController - The default controller class 5. * 6. * @author 7. * @version 8. */ 9. 10.require_once ''Zend/Controller/Action.php''; 11.require_once ''Zend/Db.php''; 12.require_once ''Zend/Registry.php''; 13.require_once ''Zend/Db/Table.php''; 14. 15.class IndexController extends Zend_Controller_Action 16.{ 17. public function init() 18. { 19. $params = array (''host'' => ''localhost'', 20. ''username'' => ''root'', 21. ''password'' => ''root'', 22. ''dbname'' => ''mysql''); 23. $db = Zend_Db::factory(''Pdo_Mysql'', $params); 24. Zend_Db_Table::setDefaultAdapter($db); 25. Zend_Registry::set(''db'', $db); 26. } 27. 28. public function indexAction() 29. { 30. $adapter = Zend_Registry::get(''db''); 31. $result = $adapter->query(''select * from user''); 32. echo $result->rowCount(); 33. echo $result->fetchAll(); 34. } 35.}
这样就能和想要连接的数据库建立连接了。
关于如何取数据,请参看下面的代码:
1.<?php 2. 3./** 4. * IndexController - The default controller class 5. * 6. * @author 7. * @version 8. */ 9. 10.require_once ''Zend/Controller/Action.php''; 11.require_once ''Zend/Db.php''; 12.require_once ''Zend/Registry.php''; 13.require_once ''Zend/Db/Table.php''; 14. 15.class IndexController extends Zend_Controller_Action 16.{ 17. public function init() 18. { 19. $params = array (''host'' => ''localhost'', 20. ''username'' => ''root'', 21. ''password'' => ''root'', 22. ''dbname'' => ''mysql''); 23. $db = Zend_Db::factory(''Pdo_Mysql'', $params); 24. Zend_Db_Table::setDefaultAdapter($db); 25. Zend_Registry::set(''db'', $db); 26. } 27. 28. public function indexAction() 29. { 30. $adapter = Zend_Registry::get(''db''); 31. $result = $adapter->query(''select * from user''); 32. echo $result->rowCount(); 33. $rowset = $result->fetchAll(); 34. foreach ($rowset as $row) { 35. echo $row[''Host'']; 36. } 37. } 38.}
注意:fetchAll方法默认只能通过字段名称取数据,如果想通过数字(所在列的位置)取需要做如下处理:
1. ...... 2. public function indexAction() 3. { 4. $adapter = Zend_Registry::get(''db''); 5. $result = $adapter->query(''select * from user''); 6. echo $result->rowCount(); 7. $rowset = $result->fetchAll(Zend_Db::FETCH_NUM); 8. foreach ($rowset as $row) { 9. echo $row[0]; 10. } 11. } |