2012-02-02 180 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

相關問題