Codeigniter 用户登录注册模块
Codeigniter 用户登录注册模块
以下皆是基于Codeigniter + MySQL
一、要实现用户登录注册功能,首先就要和MySQL数据库连接,操作流程如下:
CI中贯彻MVC模型,即Model + View + Controller。数据模型Model处理数据库的运算,视图View顾名思义即使将数据显示出来的页面,而控制器Controller是用来代理完成某项任务的PHP类,Controller充当MVC架构应用程序的“粘合剂”。再回到数据模型,通过创建控制器类,可以对数据库或者其他数据存储方式进行取回、插入和更新。CI中要使用数据库,首先要在配置文件“application/config/database.php”中对数据库进行配置,包括数据库名、用户名、密码等。以下代码段继承控制器CI_Model类,获得数据表‘news’,并对数据表‘news’进行了读和写的简单操作:
<?php class News_model extends CI_Model{ public function __construct() { $this->load->database(); } public function get_news($slug = FALSE) { if($slug == FALSE) { $query = $this->db->get('news'); //获得‘news’数据表,并将结果返回到‘query’变量中 return $query->result_array(); } $query = $this->db->get_where('news',array('slug' => $slug)); //获得‘news’数据表中主键为‘slug’的数据记录 return $query->row_array(); } public function set_news() { $this->load->helper('url'); $slug = url_title($this->input->post('title'), 'dash', TRUE); $data = array( 'title' => $this->input->post('title'), 'slug' => $slug, 'text' => $this->input->post('text') ); return $this->db->insert('news', $data); //将‘data’数据记录插入‘news’数据表中 } }
二、创建完模型CI_Model类,从数据库查询到数据之后,需要创建控制器CI_Controller类将数据模型和用来显示数据内容的视图“粘合”起来。以下代码段继承控制器CI_Controller类,调用了数据模型,控制器类获得数据模型中的数据并传递给视图显示出来:
<?php class News extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('news_model'); } public function index(){ $data['news'] = $this->news_model->get_news(); $data['title'] = 'News archive'; $this->load->view('templates/header',$data); $this->load->view('news/index',$data); $this->load->view('templates/footer',$data); } public function view($slug){ $data['news_item'] = $this->news_model->get_news($slug); if(empty($data['news_item'])){ show_404(); } $data['title'] = $data['news_item']['title']; $this->load->view('templates/header',$data); $this->load->view('news/view',$data); $this->load->view('templates/footer'); } public function create(){ $this->load->helper('form'); $this->load->library('form_validation'); $data['title'] = 'Create a news item'; $this->form_validation->set_rules('title','Title','required'); $this->form_validation->set_rules('text','text','required'); if ($this->form_validation->run() == FALSE) { $this->load->view('templates/header',$data); $this->load->view('news/create'); $this->load->view('templates/footer'); } else { $this->news_model->set_news(); $this->load->view('news/success'); } } }
三、创建完数据模型和控制器类之后,最后一件事就是创建视图View将数据显示出来。以下代码段循环显示数据库中的数据:
<?php foreach ($news as $news_item): ?> <h2><?php echo $news_item['title']?></h2> <div id = "main"> <?php echo $news_item['text']?> </div> <p><a href = "http://localhost/citest/index.php/news/<?php echo $news_item['slug']?>">View article</a></p> <?php endforeach?>