文章梗概:使用 ZendFramework 2 + 纯 sql 语句操作Mysql数据库(PDO方式)
1、config中数据库的信息(global、local文件中)可以参考 ZendFramework 2 的 Album 例子
2、假设自己写的Module名字叫Test,那么在 /module/Test/Module.php 中增加以下(假设 Test 中有 User 模块)
use Cagetest\Model\User; public function getServiceConfig(){ return array( 'factories' => array( 'Test\Model\User' => function($sm) { $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); $User = new User($dbAdapter); return $User; }, ) ); }
3、User Controller 调用 Model 的方法
/module/Test/src/Test/Controller/UserController.php
<?php namespace Test\Controller; use Zend\Mvc\Controller\AbstractActionController; use Test\Model\User; class UserController extends AbstractActionController{ protected $userModel; public function getUserModel(){ if (!$this->userModel) { $sm = $this->getServiceLocator(); $this->userModel = $sm->get('Test\Model\User'); } return $this->userModel; } public function getUserList(){ $pos = 0; $limit = 10; $list_arr = $this->getUserModel()->getUserList($pos,$limit); var_dump($list_arr); } } ?>
4、User Model 调用数据库的方法
/module/Test/src/Test/Model/User.php
<?php namespace Test\Model; class User{ protected $db; public function __construct($dbAdapter) { $this->db = $dbAdapter; } public function getUserList($pos,$limit){ $query_data = Array( ':status' => 1, ); $sql = "SELECT * FROM tbl_user WHERE status = :status limit $pos,$limit"; $sql_result = $this->db->query($sql)->execute($query_data); // 将结果集转为数组 $sql_result_arr = iterator_to_array($sql_result); // 获取结果集中的一条 $sql_result_row = $sql_result->current(); // 判断结果集是否为空 if(!$sql_result){ $return_arr = Array( 'code' => 404, 'data' => 'not found user' ); }else{ $return_arr = Array( 'code' => 200, 'data' => $sql_result_arr ); } return $return_arr; } public function createUser($mobile){ $query_data = Array( ':mobile' => $mobile, ':status' => 1, ':created_at' => date("Y-m-d H:i:s"), ); $sql = "INSERT INTO tbl_user (`mobile`,`status`,`created_at`) VALUES ( :mobile , :status , :created_at )"; $sql_result = $this->db->query($sql)->execute($query_data); // 获取受影响的行数,判断是否插入成功 $affected_rows = $sql_result->getAffectedRows(); if($affected_rows == 1){ // 插入成功,获取自增长的id $return_arr = Array( 'code' => 200, 'data' => Array( 'id' => $sql_result->getGeneratedValue(), 'mobile' => $mobile, ) ); }else{ $return_arr = Array( 'code' => 500, 'data' => 'create user failed' ); } return $return_arr; } public function updateUser($id,$mobile){ $query_data = Array( ':id' => $id, ':mobile' => $mobile, ); $sql = "UPDATE tbl_user SET `mobile` = :mobile WHERE `id` = :id"; $sql_result = $this->db->query($sql)->execute($query_data); // 获取受影响的行数,判断是否更新成功 $affected_rows = $sql_result->getAffectedRows(); if($affected_rows == 1){ // 更新成功 $return_arr = Array( 'code' => 200, 'data' => 'update user success' ); }else{ $return_arr = Array( 'code' => 500, 'data' => 'update user failed' ); } return $return_arr; } } ?>