首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在查询中迭代数组的值?

如何在查询中迭代数组的值?
EN

Stack Overflow用户
提问于 2017-08-09 21:39:30
回答 2查看 79关注 0票数 0

我想从下面的查询中迭代数组$code$per_section的值。我应该使用什么循环方法?或者这是正确的做法吗?

代码语言:javascript
复制
   //total students
    $count_query=mysql_query("select total_students from subject where teacherid = '$get_id'");
    while($count_row=mysql_fetch_array($count_query)){ 
    $total += $count_row['total_students'];
    }

    $query = mysql_query( "Select code,total_students from subject where teacherid='$get_id'");
        while($result=mysql_fetch_assoc($query))){
         $section = ($result['total_students']/ $total)*30;
         $per_section[] = round($section, 0, PHP_ROUND_HALF_UP);
         $code[] = $result['code'];
        }

    //perform this statement for a number of times depending on the number of array of $code..
        $user_query=mysql_query("select * from result where subject_id ='$code' and faculty_id = '$get_id'LIMIT $per_section ")or die(mysql_error());                   
        while($row=mysql_fetch_assoc($user_query)){
            ...
         }

示例数据:主题表

代码语言:javascript
复制
code    total_students   teacherid

IT230         45         11-0009
IT213         44         11-0009
IT214         40         11-0009

结果表

代码语言:javascript
复制
subject__id    faculty_id

IT230          11-0009
IT213          11-0009
IT214          11-0009

这是$per_section

IT230只需要学生= (45/129)*30 = 10.46,或者我只需要11个结果。

IT213只需要学生= (44/129)*30 = 10.23,或者我只需要10个结果。

IT214只需要学生= (40/129)*30 = 9.3,或者我只需要9个结果。

只有10的IT213和9的IT214。因为我只有3条记录,所以只会显示这3条记录。

EN

回答 2

Stack Overflow用户

发布于 2017-08-09 21:48:44

使用一个连接两个表的查询:

代码语言:javascript
复制
SELECT s.total_students, s.code, r.*
FROM students AS s
LEFT JOIN result AS r ON r.subject_id = s.code
WHERE s.teacher_id = '$get_id' AND r.faculty_id = '$get_id'
ORDER BY s.code

然后,您可以在单个循环中获取所有信息:

代码语言:javascript
复制
while ($result = mysqli_fetch_assoc($query)) {
    if (!isset($per_section[$result['code']]) {
        $per_section[$result['code']] = round($result['total_student']/$total*30, 0, PHP_ROUND_HALF_UP);
        $code[] = $result['code'];
    }
    if ($result['subject_id'] !== null) {
        // do stuff with columns from result table here
    }
}
票数 0
EN

Stack Overflow用户

发布于 2017-08-09 21:50:21

正如您问题的注释中所提到的,通过PDOJOIN这两个表使用预准备语句是更好的做法:

代码语言:javascript
复制
$dbh = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');

$stmt = $dbh->prepare('
    SELECT result.*
    FROM result
    JOIN student ON result.subject_id = student.code
    WHERE student.id = :id
');

$stmt->execute(['id' => $id]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45592378

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档