2012-01-02 3 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"를 실행하려고, 내가받을 이상한 결과 (아래 참조)

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) 

왜 각 레코드가 중복 :
$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); 

나는이 얻을?

답변

3

숫자 및 연관 인덱스를 모두 반환하기 때문에 이러한 현상이 발생합니다. fetch_assoc()을 사용하거나 적절한 상수 MYSQLI_ASSOC 또는 MYSQLI_NUM을 전달하여 해당 키만 반환해야합니다.


mysqli_result::fetch_array()에 대한 문서를 참조하십시오.

제쳐두고 난 실수로 잘못된 인수를 전달할 수 없도록 mysqli 클래스의 전달을 강요하기 위해 생성자에 힌트를 입력했습니다.

0

fetch_array() 메소드의 경우 the docs을 읽습니다. 두 번째 매개 변수의 기본값은 MYSQLI_BOTH입니다.