1.首先创建数据库 里面有 title text 字段
2.在 model 层
2-1 News_model 是自己创建的 Model
2-2 public function __construct() 是继承 CI框架父累方法 重写函数
class News_model extends CI_Model
{ // 确保你的 数据库配置 正确。 public function __construct() { // database 指向 数据库 在 文件夹 config/database下 parent::__construct(); $this->load->database(); } // 插入 数据 用到的函数 public function set_news($data) { return $this->db->insert('news1', $data); } }3. View 显示层
3-2 <h2><?php echo $title; ?></h2> 是根据 title从 Controller 传过来的
<h2><?php echo $title; ?></h2> <form action="http://localhost/CI/index.php/InsertController/create" method="post"> <label for="title">Title</label> <input type="input" name="title00" /><br /> <label for="text">Text</label> <input type="input" name="text00"><br /> <input type="submit" name="submit" value="创建新的item" /> </form>
4. Controller 层 最重要的 层
4-1 InsertController 是自己创建的 控制器
4-2 public function __construct() 是继承 CI框架父累方法 重写函数 4-3 $this->load->model('News_model'); 加载 model // 插入信息 class InsertController extends CI_Controller { // 构造函数 是 必须写的 继承父类 重写 父类方法 public function __construct() { parent::__construct(); $this->load->helper('url'); // 加载 model $this->load->model('News_model'); } public function create() { // 表单验证类 设置了表单验证规则 $this->load->library('form_validation'); // set_rules() 方法有三个参数:表单中字段的名称,错误信息中使用的名称, //以及验证规则。在这个例子中, 规则为 title 和 text 字段是必填的。 $this->form_validation->set_rules('title00', 'Title', 'required'); $this->form_validation->set_rules('text00', 'Text', 'required'); // $this->form_validation->run() 是CI 框架的提供的验证规则 // 如有需要可以自己写验证 // 网址 http://codeigniter.org.cn/user_guide/libraries/form_validation.html?highlight=set_rules#CI_Form_validation::set_rules // 如果表单元素为空,返回 FALSE if ($this->form_validation->run() === FALSE) { // 验证失败了 调到 插入页面 redirect('http://localhost/CI/index.php/InsertController/creat_view'); } else // 验证成功 { $data = array( 'title' => $this->input->post('title00'), 'text' => $this->input->post('text00') ); // $this->News_model->set_news($data) 返回的事bool值 // News_model 的 set_news 插入方法 if( $this->News_model->set_news($data)) { // 成功 跳转到成功页面 redirect('http://localhost/CI/index.php/InsertController/success'); } else { // 失败 跳转到 失败页面 --- 重新插入页面 redirect('http://localhost/CI/index.php/InsertController/creat_view'); } } } public function success() { $this->load->view('Success'); } public function creat_view() { $data['title'] = '从InsertController传过来的Title'; $this->load->view('InsertView', $data); } }5--- 运行效果图