首先需要打开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工程如下图所示: 测试代码如下: <?php /** *IndexController-Thedefaultcontrollerclass * *@author *@version */ require_once'Zend/Controller/Action.php'; require_once'Zend/Db.php'; require_once'Zend/ReGIStry.php'; require_once'Zend/Db/Table.php'; classIndexControllerextendsZend_Controller_Action { publicfunctioninit() { $params=array('host'=>'localhost', 'username'=>'root', 'password'=>'root', 'dbname' =>'mysql'); $db=Zend_Db::factory('Pdo_Mysql',$params); Zend_Db_Table::setDefaultAdapter($db); Zend_Registry::set('db',$db); } publicfunctionindexAction() { $adapter=Zend_Registry::get('db'); $result=$adapter->query('select*fromuser'); echo$result->rowCount(); echo$result->fetchAll(); } }
这样就能和想要连接的数据库建立连接了。 关于如何取数据,请参看下面的代码: <?php /** *IndexController-Thedefaultcontrollerclass * *@author *@version */ require_once'Zend/Controller/Action.php'; require_once'Zend/Db.php'; require_once'Zend/Registry.php'; require_once'Zend/Db/Table.php'; classIndexControllerextendsZend_Controller_Action { publicfunctioninit() { $params=array('host'=>'localhost', 'username'=>'root', 'password'=>'root', 'dbname' =>'mysql'); $db=Zend_Db::factory('Pdo_Mysql',$params); Zend_Db_Table::setDefaultAdapter($db); Zend_Registry::set('db',$db); } publicfunctionindexAction() { $adapter=Zend_Registry::get('db'); $result=$adapter->query('select*fromuser'); echo$result->rowCount(); $rowset=$result->fetchAll(); foreach($rowsetas$row){ echo$row['Host']; } } }
注意:fetchAll方法默认只能通过字段名称取数据,如果想通过数字(所在列的位置)取需要做如下处理: ...... publicfunctionindexAction() { $adapter=Zend_Registry::get('db'); $result=$adapter->query('select*fromuser'); echo$result->rowCount(); $rowset=$result->fetchAll(Zend_Db::FETCH_NUM); foreach($rowsetas$row){ echo$row[0]; } }
(责任编辑:admin) |