ZendFrame實現一個投票模組
來源:互聯網
上載者:User
思路分析:擷取使用者ip,判斷該ip 是否被禁用,然後判斷今天有沒有投了 再做出相應的操作... 主要步驟如下: 配置一下application.ini 讓項目可以串連到指定的資料庫 [mysql]db.adapter = PDO_MYSQLdb.params.host = localhostdb.params.username = rootdb.params.password =db.params.dbname=votedb 初始化資料庫適配器 <?php // 做一個父類,專門供其它控制器來繼承的 class BaseController extends Zend_Controller_Action{ public function init(){ //初始化資料庫適配器 $url = constant("APPLICATION_PATH").DIRECTORY_SEPARATOR.'configs'.DIRECTORY_SEPARATOR.'application.ini'; $dbconfig = new Zend_Config_Ini($url,"mysql"); $db = Zend_Db::factory($dbconfig->db); Zend_Db_Table::setDefaultAdapter($db); } } //建立表模型 <?php//這裡一定要繼承Zend_db_Table,否則就不是表模型 class Item extends Zend_Db_Table{ protected $_name = 'item'; }//投票控制器 <?phprequire_once 'BaseController.php';require_once APPLICATION_PATH.'/models/Item.php';require_once APPLICATION_PATH.'/models/Filter.php';require_once APPLICATION_PATH.'/models/VoteLog.php'; class VoteController extends BaseController{public function voteAction(){ $item_id = $this->getRequest()->getParam('itemid','no'); //擷取id//用於擷取ip 地址$_SERVER['REMOTE_ADDR'] $ip = $this->getRequest()->getServer('REMOTE_ADDR'); //看看這個ip是否被禁用 $filterModel = new Filter(); $filters = $filterModel->fetchAll("ip='$ip'")->toArray(); if(count($filters)>=1){ $this->view->info="你被警用了!"; //成功,跳轉到一個全域的視圖 $this->_forward('err','global'); return; } //先看voteLOg 這個表今天有沒有透過一次$today=date('Ymd');//今天的時間$voteLogModel = new VoteLog();$where = "ip='$ip' AND vote_date=$today";$res = $voteLogModel->fetchAll($where)->toArray();if(count($res)>0){ //如果大於0表示已經投 了$this->render('error');return ;}else{//更新item的vote_count,添加更新日誌$data = array('ip' => $ip,'vote_date'=>$today,'item_id'=>$item_id);if($voteLogModel->insert($data)>0){ //如果更新成功要更改item 表$itemModel = new Item();//通過主鍵直接擷取對應的item$item = $itemModel->find($item_id)->toArray(); $newvote = $item[0]['vote_count']+1;$set = array('vote_count'=>$newvote);$where = "id=$item_id";$itemModel->update($set, $where);}$this->render('ok');}}} ?>