如何最小化代码并避免重复?

时间:2015-04-25 04:43:45

标签: php

我正在学习PHP。

我想计算考试中所有科目的班级缺席学生人数。

我使用以下代码提取一个班级和2个科目的数据。

我想计算四个班级和27个科目的缺席学生人数如何通过使用最少的代码和避免重复来实现这一目标?

<?php


/*Query to calculate number of absent students in FYBA in all 6 subjects.  

by counting studid (student id)  

Economics = marks1e*/


$e = mysql_query('select count(studid) from examdbf1 where exam_id =   14153 and faculty = 1 and sem = 1 and repeater = 1 and marks1e = \'AA\'');

$ea = mysql_fetch_array($e);

echo '<br>'. $ea['count(studid)'] . '<br>';


/*Marathi Optional = marks2e*/


$mo = mysql_query('select count(studid) from examdbf1 where exam_id = 14153 and faculty = 1 and sem = 1 and repeater = 1 and marks2e = \'AA\'');

$moa = mysql_fetch_array($mo);

echo '<br>'. $moa['count(studid)'] . '<br>';

1 个答案:

答案 0 :(得分:0)

使用评论中的代码,将***marks1e***更改为$m[$x] -

$m = array("marks1e", "marks2e", "marks3e", "marks4e", "marks5e", "marks6e"); 
$mcount = count($m); 
for($x = 0; $x < $mcount; $x++) { 
    $e = mysql_query('SELECT count(studid) FROM examdbf1 WHERE exam_id = 14153 AND faculty = 1 AND sem = 1 AND repeater = 1 AND '.$m[$x].' = \'AA\''); 
    $ea = mysql_fetch_array($e); 
    echo '<br>'.$m[$x].': '. $ea['count(studid)'] . '<br>';
}

同样,由于您只是更改了$m的值,因此您可以执行foreach() -

$m = array("marks1e", "marks2e", "marks3e", "marks4e", "marks5e", "marks6e"); 
foreach($m as $n) { 
    $e = mysql_query('SELECT count(studid) FROM examdbf1 WHERE exam_id = 14153 AND faculty = 1 AND sem = 1 AND repeater = 1 AND '.$n.' = \'AA\''); 
    $ea = mysql_fetch_array($e); 
    echo '<br>'.$n.': '. $ea['count(studid)'] . '<br>';
}