ZendFrameWork3 連接數(shù)據(jù)庫MySQL
第一步:清理默認(rèn)配置
剛安裝好的代碼目錄里面有些自帶的代碼桨仿、文件及目錄是不需要的么鹤,處理 config目錄保留以下文件
config目錄
第二步:配置數(shù)據(jù)庫連接
編輯 config/autoload/global.php 文件內(nèi)容如下:
<?php
return [
//數(shù)據(jù)庫連接配置
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=數(shù)據(jù)庫表名;host=數(shù)據(jù)庫IP;port=數(shù)據(jù)庫端口',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
PDO::MYSQL_ATTR_FOUND_ROWS => 2
),
),
//配置數(shù)據(jù)庫適配器
'service_manager' => [
'factories' => [
'Zend\Db\Adapter\Adapter' => function ($container) {
$adapterFactory = new \Zend\Db\Adapter\AdapterServiceFactory ();
$adapter = $adapterFactory->createService($container);
return $adapter;
},
],
],
//在view_manager中創(chuàng)建策略,前臺能接收調(diào)用返回的jsonModel輸出json的數(shù)據(jù)
'view_manager' => [
'strategies' => array(
'ViewJsonStrategy',
),
]
];
編輯 config/autoload/local.php 文件內(nèi)容如下:
<?php
return array(
'db' => array(
'username' => 數(shù)據(jù)庫連接賬號,
'password' => 數(shù)據(jù)庫連接密碼
),
);
編輯config/application.config.php 文件里配置如下
#....
//是否允許配置緩存棋返,為不影響調(diào)試延都,設(shè)置為不允許耘沼。
'config_cache_enabled' => false,
#....
在數(shù)據(jù)庫創(chuàng)建一個Articles表良蒸,表字段設(shè)置如下
Articles表
插入幾條數(shù)據(jù)進(jìn)行接下來的測試透且。
修改module/Application/src/Controller/IndexController.php內(nèi)容如下:
<?php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\Db\ResultSet\ResultSet;
class IndexController extends AbstractActionController
{
public function indexAction()
{
//獲取數(shù)據(jù)庫服務(wù)管理器
$dbAdapter = $this->getEvent()->getApplication()->getServiceManager()->get('Zend\Db\Adapter\Adapter');
//查詢語句
$sql = "select * from articles";
//執(zhí)行
$statement = $dbAdapter->createStatement($sql);
$result = $statement->execute();
//格式化輸出
$resultSet = new ResultSet();
$resultSet->initialize($result);
//返回?cái)?shù)據(jù)前臺
return new JsonModel(array('result' => true, 'msg' => $resultSet->toArray()));
}
}
打開瀏覽器訪問http://127.0.0.1株旷,通過F12調(diào)試工具查看返回娘摔。
Chrome DevTools
至此系統(tǒng)可以直接訪問查詢數(shù)據(jù)庫數(shù)據(jù)碰煌。