行的总百分比,基于查询的结果集

时间:2016-02-07 12:09:11

标签: php mysql arrays mysqli

填写此表第二列的最佳方法是什么?

enter image description here

我想在“课堂时间百分比”栏中显示此公式的结果:

= time spent on topic / total time spent on topic * 100

所有值都来自MySql数据库。

这是我在上表中显示数据的代码

$query=mysqli_query($con,
    "select * from test_validity_items
     where test_validity_id='".$_GET['test_v_id']."'");
$i=0;
while($row=mysqli_fetch_array($query))
{ 
    $i++;

    <tr>        
        <td><center><?php echo $row['test_items_time_spent'];?> </center></td>                              
        <td><center><?php echo $row['test_items_percent_class_time'];?></center></td>
    </tr>
}

1 个答案:

答案 0 :(得分:0)

这可以在您的SQL语句中完成。您当前的SELECT如下所示:

 SELECT  *
 FROM    test_validity_items
 WHERE   test_validity_id='...'

其中点表示从请求中检索的值。

您可以在上述SQL中将百分比添加为计算列,如下所示:

SELECT  test_items_time_spent,
        test_items_time_spent * 100
            / (SELECT SUM(test_items_time_spent)
               FROM   test_validity_items
               WHERE  t.test_validity_id = test_validity_id)
        AS test_items_percent_class_time
FROM    test_validity_items t
WHERE   test_validity_id='...'

这是SQL fiddle

小心,当您在WHERE子句中添加其他条件时,也始终在内部子查询中添加相同的条件。

更改现有的PHP代码,这将成为:

<?php
$query=mysqli_query($con,
    "select test_items_time_spent,
            test_items_time_spent * 100
                / (SELECT SUM(test_items_time_spent)
                   FROM   test_validity_items
                   WHERE  t.test_validity_id = test_validity_id)
            AS test_items_percent_class_time
     from   test_validity_items
     where  test_validity_id='".$_GET['test_v_id']."'");
$i=0;
while($row=mysqli_fetch_array($query))
{ 
    $i++;
?>    
    <tr>        
        <td><center><?php echo $row['test_items_time_spent'];?> </center></td>                              
        <td><center><?php echo $row['test_items_percent_class_time'];?></center></td>
    </tr>
<?php
}
?>

SQL注入

请注意,您的代码很容易受到SQL注入攻击。将$_GET值连接到SQL是不安全的。您应该使用prepared statements代替并将参数单独传递给MySql。