用php确定百分比

时间:2013-03-26 16:12:05

标签: php mysql percentage

我正在尝试确定在第一次尝试或第二次尝试时通过测试的学生人数的百分比。我相信我的代码是正确的,但是当我回显结果时,我没有输出。

<?php
$NREMT1 = "SELECT nremtcognitive FROM course_students WHERE nremtcognitive = '1' ";
$NREMT2 = "SELECT nremtcognitive FROM course_students WHERE nremtcognitive >= '2' ";
$completed = "SELECT studentstatus FROM course_students WHERE studentstatus >='4'";

$getNREMT1 = mysql_query($NREMT1);
$fetchNREMT1= mysql_num_rows($getNREMT1);
$getNREMT2 = mysql_query($NREMT2);
$fetchNREMT2= mysql_num_rows($getNREMT2);
$getcompleted = mysql_query($completed);
$fetchcompleted= mysql_num_rows($getcompleted);

function percent($fetchNREMT1, $fetchNREMT2, $fetchcompleted) {
    $NREMT1count= $fetchNREMT1/$fetchcompleted;
    $NREMT1percent= $NREMT1count * 100;
    $NREMT1result = number_format($NREMT1percent,0);

    $NREMT2count= $fetchNREMT2/$fetchcompleted;
    $NREMT2percent= $NREMT2count * 100;
    $NREMT2result = number_format($NREMT2percent,0);
}
echo $NREMT1result;
echo $NREMT2result;

?>

3 个答案:

答案 0 :(得分:0)

您没有在任何地方调用您的函数percent

您应该将其称为并使其返回或其他方式,只是可以避免创建它并将相同的代码放在同一位置:

 $NREMT1count= $fetchNREMT1/$fetchcompleted;
 $NREMT1percent= $NREMT1count * 100;
 $NREMT1result = number_format($NREMT1percent,0);

 $NREMT2count= $fetchNREMT2/$fetchcompleted;
 $NREMT2percent= $NREMT2count * 100;
 $NREMT2result = number_format($NREMT2percent,0);

 echo $NREMT1result;
 echo $NREMT2result;

您似乎并不清楚功能的概念。您可以查看the documentation

答案 1 :(得分:0)

您的问题是,percent()内声明的变量永远不会被初始化,因为函数永远不会被调用。试试这个:

<?php
$NREMT1 = "SELECT nremtcognitive FROM course_students WHERE nremtcognitive = '1' ";
$NREMT2 = "SELECT nremtcognitive FROM course_students WHERE nremtcognitive >= '2' ";
$completed = "SELECT studentstatus FROM course_students WHERE studentstatus >='4'";

$getNREMT1 = mysql_query($NREMT1);
$fetchNREMT1= mysql_num_rows($getNREMT1);
$getNREMT2 = mysql_query($NREMT2);
$fetchNREMT2= mysql_num_rows($getNREMT2);
$getcompleted = mysql_query($completed);
$fetchcompleted= mysql_num_rows($getcompleted);

percent($fetchNREMT1, $fetchNREMT2, $fetchcompleted);

function percent($fetchNREMT1, $fetchNREMT2, $fetchcompleted) {
    $NREMT1count= $fetchNREMT1/$fetchcompleted;
    $NREMT1percent= $NREMT1count * 100;
    $NREMT1result = number_format($NREMT1percent,0);

    $NREMT2count= $fetchNREMT2/$fetchcompleted;
    $NREMT2percent= $NREMT2count * 100;
    $NREMT2result = number_format($NREMT2percent,0);

    echo $NREMT1result;
    echo $NREMT2result;
}
?>

值得注意的是,mysql_*系列函数现已弃用,您应该考虑使用MySQLi或PDO。

答案 2 :(得分:0)

只需更改您的查询即可。未经测试,但这应该让你开始:

SELECT 
    SUM(IF(CONVERT(nremtcognitive, UNSIGNED INTEGER) >= 2)) / COUNT(*) 
FROM course_students;
相关问题