如何使用CodeIgniter将数据从控制器发送到模型

时间:2015-02-27 13:09:11

标签: php codeigniter

我是CI的新手,我使用CI v.2.2.1,我希望从我的控制器发送数据到模型,但我在这里遇到了一些麻烦。错误说我的模型是undefined property。这是我的代码:

控制器: users.php

public function postUser(){
    $username = $this->input->post('username');
    $password = $this->input->post('password');
    $email = $this->input->post('email');
    $phone = $this->input->post('phone');
    $address = $this->input->post('address');
    $level = $this->input->post('level');
    $status = $this->input->post('status');
    $this->load->model('model_crud');
    $query = $this->model_crud->insert('Users',$_POST);
    echo "$query";
}

型号: model_crud.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Model_crud extends CI_Model {
    public function __construct(){
         parent::__construct();
    }

    public function insert($table,$data){
        $query = $this->db->insert($table,$data);
        return $query;
    }
}

是否有任何配置使用模型或我的代码是错误的? 谁能帮我 ? THX

2 个答案:

答案 0 :(得分:1)

第一件事,您没有提供有关错误的足够信息。 模型是否随处可见?从控制器中以这种方式加载模型:

$this->load->model('model_crud');

或者你可以通过修改你的autolad.php配置文件来预加载它

postUser()中的

- 您获取了自己的帖子数据,但并未真正使用它。相反,您正在传递整个全局$ _POST,这可能是脏的和不安全的。我建议在从POST形成数据数组时使用CodeIgniter的XSS过滤:

$data = array (
  'username' => $this->input->post('username', TRUE); //TRUE identifies you're passing your data through XSS filter,
 //all other elements
);

最后:

$query = $this->model_crud->insert('Users',$data);

答案 1 :(得分:0)

您可以通过将数组发送到模型并将表列名称作为键来执行此操作:

控制器:

$data = array(
      'username' => $this->input->post('username') ,
      'password ' => $this->input->post('password') ,
       ...
   );
// 'TABLE COLUMN NAME' => "VALUE"

$query = $this->model_crud->insert('Users',$data);
echo "$query";
相关问题