我有以下“课程”课程:
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 )
为什么每条记录都重复?
答案 0 :(得分:3)
这种情况正在发生,因为您正在返回数字和关联索引。您应该使用fetch_assoc()
或传递相应的常量MYSQLI_ASSOC
或MYSQLI_NUM
来返回这些键。
请参阅mysqli_result::fetch_array()
上的文档。
顺便说一下,我会输入提示你的构造函数来强制传递mysqli
类,这样你就不会意外地传递一个无效的参数。
答案 1 :(得分:0)
读取the docs以获取fetch_array()方法。第二个参数默认为MYSQLI_BOTH。