2012-02-18 86 views
0

我有以下模型函數,我想知道如何改進它,並在需要時拉出需要的$row,這樣我就不會收到PHP錯誤。查詢改進:foreach

如何,我拉着所需的數據:

$data['companyName'] = $this->core_model->companyDetails('coreCompanyName'); 

錯誤:

Undefined property: stdClass::$coreContactName 
Undefined property: stdClass::$coreContactEmail 

型號:

function companyDetails() 
{ 
    $this->db->select('coreCompanyName, coreContactName, coreContactEmail'); 

    $this->db->from('core'); 

    $whereData = array('coreCompanyName' => $companyName, 'coreContactName' => $companyContactName, 'coreContactEmail' => $companyContactEmail); 

    $this->db->where($whereData); 

    $query = $this->db->get(); 

    $result = ''; 

    if ($query->num_rows() > 0) 
    { 

     foreach ($query->result() as $row) 
     { 
      $result .= $row->coreCompanyName; 
      $result .= $row->coreContactName; 
      $result .= $row->coreContactEmail; 
     } 
    } 
    return $result; 
} 
+0

在foreach之後,'$ row'的'print_r'給你什麼? – 2012-02-18 03:56:39

回答

0
<?php 

/** 
* 
* WHERE ARE : $companyName, $companyContactName, $companyContactEmail being defined ? 
* WHY return 'companyName' WHEN You are quering based on the '$companyName' ??? 
* Your query wil fail with out it, that that's all your using ? 
* 
*/ 
function companyDetails() { 

    $query = $this->db->query("SELECT companyName FROM core WHERE coreCompanyName = ? AND coreContactName = ? AND coreContactEmail = ? LIMIT 1", 
    array($companyName, $companyContactName, $companyContactEmail)); 
    return ($query->num_rows() == 1) ? $query->row()->companyName : FALSE; 

} 
1

IT方面HOULD是這樣

$this->db->select('coreCompanyName, coreContactName, coreContactEmail'); 

$this->db->select('coreCompanyName','coreContactName','coreContactEmail'); 

參見參考http://codeigniter.com/user_guide/database/active_record.html#select

要限制到一組特定的記錄,使用其中()函數。例如

$this->db->where('companyId', $companyId); 
+0

謝謝Chui,但現在將所有數據從表格中取出,而不是所需的數據。有任何想法嗎? – 2012-02-18 03:59:52

+0

我添加了一個如何在答案中過濾的示例。你想過濾什麼? – 2012-02-18 07:58:46

0

變化:

$this->db->select('coreCompanyName','coreContactName','coreContactEmail'); 

要:

$this->db->select('coreCompanyName, coreContactName, coreContactEmail'); 

現在,你說的這個拉的所有數據,但實際上並沒有過濾的結果。我不知道需要的數據是什麼

+0

我想這就是我的問題是我不確定如何過濾結果什麼是最好的方式來攻擊這個。我現在將上傳一個調整後的模型 – 2012-02-18 04:25:17