简体   繁体   中英

Row's percentage of total, based on query's result set

What is the best way to fill the second column of this table?

在此处输入图片说明

I want to display in the "Percent of class time" column the result of this formula:

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

All the values come from the MySql database.

Here's my code to display data in the above table

$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>
}

This can be done in your SQL statement. Your current SELECT looks like this:

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

where the dots represent a value retrieved from the request.

You can add the percentage as a calculated column in the above SQL, like this:

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='...'

Here is a SQL fiddle

Be careful , when you add other conditions in the WHERE clause, to always add the same conditions in the inner sub-query as well.

Altering your existing PHP code, this becomes:

<?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 Injection

Please be warned that your code is vulnerable to SQL injection. It is not safe to concatenate $_GET values to your SQL. You should use prepared statements instead and pass the parameter to MySql separately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM