2011-12-13 65 views
0

我需要數據庫驗證錯誤的幫助。驗證錯誤數據庫在codeigniter

我有一個模型:

function total ($id_student, $id_course){ 
     $query = $this->db->query('select total from student where id_student='.$id_student. ' and $id_course='.$id_course); 
     if ($query->num_rows() <= 0) { 
      return false; 

     } 
     if ($query->num_rows() > 0) { 
      $row = $query->row(); 
      return $row->total; 
     } 
    } 

我有這樣的代碼在控制器:

$id_course=array; 
$total = array(); 
     for ($i = 0; $i < count($list_courses); $i++) {    
      $total[$i] = $this->student_model->total($id_student, $id_course[$i]); 
      $error[$i]= $this->db->_error_message(); 
      if(!empty($error[$i])){ 
        $total[$i] = 0;      
       } 
     } 

參數$ id_student和$ id_course可以在數據庫中存在或沒有。我需要,如果查詢給出錯誤或者查詢不存在,跳過錯誤,執行$ total [$ i] = 0並且不顯示錯誤數據庫並繼續循環。我不知道我該怎麼做。我在論壇上嘗試過很多選項,但是我做不到。謝謝你的幫助。我很抱歉我的英語。

+0

有(我希望)在您的代碼中的一些拼寫錯誤;從學生選擇總數id_student ='。$ id_student。 '和id_course ='。$ id_course和$ id_course = array(); – Rooneyl

回答

1

在您的模型方法中,如果查詢不產生結果,則返回false。所以你可以這樣做:

$id_course=array; 
$total = array(); 
for ($i = 0; $i < count($list_courses); $i++) { 

    // if query returns false, then $total[$i] will be false   
    $total[$i] = $this->student_model->total($id_student, $id_course[$i]); 
    $error[$i]= $this->db->_error_message(); 

    // check if $total[$i] is empty/false, if so make it 0 
    if(empty($total[$i])){ 
     $total[$i] = 0;      
    } 
} 
+0

非常感謝。我測試了你的答案,它的工作原理。 – cabita

1

我會改變模型的功能;

public function total ($id_student, $id_course){ 
    $sql = "SELECT `total` FROM `student` WHERE `id_student` = ? AND `id_course` = ? LIMIT 1"; 
    // to prevent any sql injection, use binding 
    $query = $this->db->query($sql, array($id_student, $id_course); 
    if ($query->num_rows() > 0) { 
     $row = $query->row(0); 
     return $row->total; 
    } else { 
     return 0; 
    } 
} 

然後將控制器更改爲;

$id_course = array(); 
$total = array(); 
// why not use a foreach loop? 
for ($i = 0; $i < count($list_courses); $i++) { 
    $result = $this->student_model->total($id_student, $id_course[$i]); 
    if ($result == 0) { 
     $error[$i]= $this->db->_error_message(); 
    } 
    $total[$i] = $result; 
} 

通過從模型返回0而不是FALSE它可以直接進入控制器功能。

+0

感謝您的回答。 – cabita