2012-01-02 81 views
0

我有以下的「課程」類:PHP OOP:奇怪的數組返回

class Course { 
    // The constructor just sets the database object 
    public function __construct($mysqli) { 
     $this->mysqli = $mysqli; 
    } 
    public function getCourseInfoByID($id) { 
     $result = $this->mysqli->query("SELECT * FROM courses WHERE id='$id'"); 
     $course_info = $result->fetch_array(); 

     // If found, return the student object 
     if($course_info) { 
      return $course_info; 
     } 
     return FALSE; 
    } 
} 

當我聲明類並嘗試運行功能「getCourseInfoByID」,我得到奇怪的結果(見下文)

$cid = process_get_request('cid'); 
$course = new Course($mysqli); 

if(! $course_info = $course->getCourseInfoByID($cid)) { 
    $error[] = "Invalid Course ID"; 
    setError(); 
    redirectTo("instructors.php"); 
} 
print_r($course_info); 

我得到這個:

Array ([0] => 2 [id] => 2 [1] => 1 [course_type_id] => 1 [2] => 1 [instructor_id] => 1 [3] => Tooele [dz_name] => Tooele [4] => 4 Airport Road [dz_address] => 4 Airport Road [5] => Tooele [dz_city] => Tooele [6] => Utah [dz_state] => Utah [7] => 84020 [dz_zip] => 84020 [8] => [dz_email] => [9] => 2011-12-30 17:25:12 [created] => 2011-12-30 17:25:12 [10] => 2012-01-02 16:24:08 [start_date] => 2012-01-02 16:24:08 [11] => 2012-01-08 16:24:17 [end_date] => 2012-01-08 16:24:17 [12] => 10 [student_slots] => 10 [13] => Brett will also be assisting in teaching this course as Nathan's assistant. Brett paid Nathan quite well to be his assistant. [notes] => Brett will also be assisting in teaching this course as Nathan's assistant. Brett paid Nathan quite well to be his assistant. [14] => 0 [approved_by] => 0 [15] => 0000-00-00 00:00:00 [approved_on] => 0000-00-00 00:00:00 [16] => 0 [completed] => 0) 

爲什麼每個記錄複製?

回答

3

發生這種情況是因爲您正在返回數字和關聯索引。您應該使用fetch_assoc()或傳遞適當的常量MYSQLI_ASSOCMYSQLI_NUM以返回這些密鑰。


查看關於mysqli_result::fetch_array()的文檔。

另外我會輸入提示你的構造函數強制傳遞一個mysqli類,這樣你就不會無意中傳遞一個無效的參數。

0

對於fetch_array()方法,請閱讀the docs。第二個參數默認爲MYSQLI_BOTH。