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


how to send data from controller to model with 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

首先,您没有提供足够的错误信息。这个模型装在哪儿了吗?通过控制器,您可以通过以下方式加载模型:

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

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

在postUser()中-你正在获取你的post数据,但并没有真正使用它。相反,你正在传递整个全局$_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);

您可以通过向模型发送一个以表列名为键的数组来实现这一点:

控制器:

$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";