【问题标题】:Codeigniter, Passing a variable from a model to a controllerCodeigniter,将变量从模型传递到控制器
【发布时间】:2012-02-02 01:30:42
【问题描述】:

Codeigniter 和 PHP 新手。

我想从数据库中检索单个位数据,将该单个位数据转换为变量并将其传递给控制器​​并将该数据用作单个变量?例如,我可以使用控制器中的数据执行 if $string=$string 等操作。

如果有人能提供模型和控制器的示例,我们将不胜感激。

【问题讨论】:

  • 将此答案标记为“已接受”,海报! :)

标签: codeigniter variables model controller


【解决方案1】:

这很简单,taken right from CodeIgniter's documentation,你绝对应该通读一遍(代码中的 cmets 主要是我的):

控制者

class Blog_controller extends CI_Controller {

    function blog()
    {
        // Load the Blog model so we can get some data
        $this->load->model('Blog');

        // Call "get_last_ten_entries" function and assign its result to a variable
        $data['query'] = $this->Blog->get_last_ten_entries();

        // Load view and pass our variable to display data to the user
        $this->load->view('blog', $data);
    }
}

模型

class Blogmodel extends CI_Model {

    var $title   = '';
    var $content = '';
    var $date    = '';

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }

    // Query the database to get some data and return the result
    function get_last_ten_entries()
    {
        $query = $this->db->get('entries', 10);
        return $query->result();
    }

    // ... truncated for brevity

}

编辑

这是非常基本的东西,我强烈推荐 reading through the documentation 和 walking through some tutorials,但无论如何我会尽力提供帮助:

根据您在下面的评论,您需要以下内容(诚然,这很模糊):

  1. 从查询中获取一位数据
  2. 将其传递给变量(您的意思是“将其分配给变量”吗?)
  3. 验证数据库中的那部分数据

请仔细阅读Database class documentation。这实际上取决于您正在运行的特定查询以及您想要从中获取的数据。根据上面的示例,在您的模型中的某些函数中它可能看起来像这样(请记住,这完全是任意的,因为我不知道您的查询是什么样的或您想要什么数据):

// Get a single entry record
$query = $this->db->get('entries', 1);

// Did the query return a single record?
if($query->num_rows() === 1){

    // It returned a result
    // Get a single value from the record and assign it to a variable
    $your_variable = $this->query()->row()->SOME_VALUE_FROM_RETURNED_RECORD;

    // "Validate" the variable.
    // This is incredibly vague, but you do whatever you want with the value here
    // e.g. pass it to some "validator" function, return it to the controller, etc.
    if($your_variable == $some_other_value){
        // It validated!
    } else {
        // It did not validate
    }

} else {
    // It did not return any results
}

【讨论】:

  • 感谢科林的帮助。只是试图更深入地解释这一点。我想从查询中获取一点数据并将其传递给一个变量,而不是使用它来将其传递给视图,而是验证数据库中的那部分数据。所以...从数据库中获取单个数据检查 $data = $data..
  • 谢谢,非常感谢。很有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多