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.