gpt4 book ai didi

PHP/MYSQL Loop 只迭代一次,无法将数据存储到数组中

转载 作者:行者123 更新时间:2023-11-29 04:05:27 38 4
gpt4 key购买 nike

我有以下一段代码,它连接两个表,然后返回 users 表中的所有教师用户。

有资格成为教师的用户,然后从teachers 表中检索信息

所以假设 users 表中有 3 个用户符合教师资格,所有这 3 个用户都应该存储在一个数组中。

页面加载时数组变空

SQL语句

//IF my reasoning is correct the folllowing sql query should select alll users who qualifies as teachers
$sql = "SELECT users.*, teachers.*
FROM users INNER JOIN teachers ON teachers.userID = users.userID";

功能

public function showAllTeachers()
{
$db = DB::getInstance();
$sql = "SELECT users.*, teachers.*
FROM users INNER JOIN teachers ON teachers.userID = users.userID";

//simple DB QUERY
$stmnt = $db->prepare($sql);
$stmnt->execute();
$teachers = $stmnt->fetchAll();
$teacherInfo = array();

//Check if there are any users who qualifies as teachers else return fals
if ($stmnt->rowCount() > 0) {
foreach($teachers as $teacher){
//Store all teacher info in array $teacherInfo
//There are more than 1 teacher so loop shouldl iterate more than once

$teacherInfo = array('name' =>$teacher['firstname'], 'headline' =>$teacher['headline'], 'location' => $teacher['location'],
'age' => $teacher['age'], 'experience' => $teacher['experience'], 'imgPath' => $teacher['imgPath']);
}//foreach

//return array with teacher info
return $teacherInfo;
}//rowcount
else {
return false; //no teachers
}
}//function

因为有超过 1 个用户有资格成为教师 $teacherInfo 现在应该包含所有这些教师的数据

清空数组

以下内容在页面加载时运行,应该会显示所有教师。

我的问题当清空数组 $allTeachers 时,我只得到一个结果(老师)。因此我的循环出于某种原因只迭代一次

 $teachers = new TeacherSearch();
$allTeachers = $teachers->showAllTeachers();
if(is_array($allTeachers)){
foreach($allTeachers as $key => $teacher){
echo $key;
echo $teacher;
echo '<br />';
}
}

非常感谢任何帮助

附加信息

数据库

enter image description here

教师表

enter image description here

用户表

enter image description here

用户表数据

enter image description here

最佳答案

好像不是你的循环只执行一次的问题,在里面加上echo 'test',你会看到它执行了多次(只要$teachers 当然有不止一个元素。

问题是您在每个 foreach 循环执行时覆盖了 $teacherInfo,而不是向其附加一个新数组。

替换:

$teacherInfo = array('name' =>$teacher['firstname'], 'headline' =>$teacher['headline'], 'location' => $teacher['location'],
'age' => $teacher['age'], 'experience' => $teacher['experience'], 'imgPath' => $teacher['imgPath']);

与:

$teacherInfo[] = array('name' =>$teacher['firstname'], 'headline' =>$teacher['headline'], 'location' => $teacher['location'],
'age' => $teacher['age'], 'experience' => $teacher['experience'], 'imgPath' => $teacher['imgPath']);

关于PHP/MYSQL Loop 只迭代一次,无法将数据存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45231881/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com