从table1中选择id为table2中记录的记录

问题描述 投票:0回答:1

我有两张桌子;教师表和班级表如下图:

桌老师 id 名称 类 1 - 约翰 - 1,3,4 2 - 弗雷德 - 1,2 3 - 格蕾丝 - 4 4 - 杰克 - 2,3

表类 id 名称 类代码 1 - 幼儿园1 - KG1 2 - 幼儿园2 - KG2 3 - 幼儿园1 - NS1 4 - 幼儿园2 - NS2

我想在 PHP 表格中显示所有老师的姓名和他们教授的课程;

1. selecting name from teacher table
2. selecting class from class table based on class ids that has been assigned to the teacher in teacher table. I have no problem in displaying the names of teachers and also displaying the classes assigned to the teacher when the classes assigned to the teacher has their ids with single digit id.

但是问题是当创建了更多的类并且它们的id是两位数或更多时,就会显示以下错误;

警告:尝试访问 int 类型值的数组偏移量

以下是使用的代码;

 <?php 

$c = '';
$classes = str_split(trim($teacher['class']));
foreach ($classes as $class) {
$c_temp = getClassById($class, $conn);
if ($c_temp != 0) 
$c .=$c_temp['class_code'].', ';
}
echo $c;

 ?>
php mysqli
1个回答
0
投票

如果你使用mysql,你可以试试这个:

<?php
    $teacherQuery = mysqli_query($mysqlConn, "SELECT * FROM teachers");
    while($rowTeacher = mysqli_fetch_array($teacherQuery)){
        list($className, $classCode) = mysqli_fetch_array(mysqli_query($mysqlConn, "SELECT GROUP_CONCAT(name), GROUP_CONCAT(class_code) FROM classes WHERE '$rowTeacher[class]' LIKE CONCAT('%', id, '%')"));
        echo '<br>';
        echo 'ID: '.$rowTeacher['id'];
        echo '<br>';
        echo 'Teacher name: '.$rowTeacher['name'];
        echo '<br>';
        echo 'Class name: '.($className ?? 'Class name not found');
        echo '<br>';
        echo 'Class code: '.($classCode ?? 'Class code not found');
        echo '<br>';
    }
© www.soinside.com 2019 - 2024. All rights reserved.