2012-02-02 183 views
2

Codeigniter的新功能& PHP。Codeigniter,将模型中的变量传递给控制器​​

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

如果有人能够提供一个模型和控制器的例子,将不胜感激。

+0

马克这个答案是“ACCEPTED”,海报! :) – 2013-12-03 22:29:19

回答

5

这是非常简单和taken right from CodeIgniter's documentation,你一定要通读(代码中的注释大多是我的):

的控制器

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 documentationwalking 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 
} 
+0

谢谢科林的帮助。只是试图更深入地解释这一点。我想从查询中获取一点数据,并将其传递给一个变量,而不是用它将它传递给一个视图,而是从数据库中验证那一点数据。所以...从数据库中获取一位数据,检查$ data = $ data .. – 2012-02-02 10:59:15

+0

@AlexStacey:请参阅上面的我的编辑。 – 2012-02-02 17:33:46

+0

谢谢,最感谢。很有帮助。 – 2012-02-02 19:05:41

相关问题