Zeroic
Zeroic

Reputation: 251

Mathematics in PHP

I am a beginner here. I have two questions.

This is my query:

$result = mysql_query( "select SUM(achievenum) as achieve_rows from games" );
$row = mysql_fetch_object( $result );
$total_achieve = $row->achieve_rows;

$result = mysql_query( "select SUM(achieveget) as get_rows from games" );
$row = mysql_fetch_object( $result );
$get_achieve = $row->get_rows;

$completed_rate = $get_achieve * 100 / $total_achieve;
  1. How can I make this code with one query instead of two?

  2. When I display the percentage

it shows

Completion Rate : 32.3529411765% 

I need it to show only the first three numbers.

32.3 %

Upvotes: 0

Views: 92

Answers (2)

piyush
piyush

Reputation: 976

The query would be :

select ROUND(SUM(achieveget)*100/SUM(achievenum),1) as completion_rate from games

Upvotes: 3

Fluffeh
Fluffeh

Reputation: 33504

To modify your sql use this:

select 
    SUM(achievenum) as achieve_rows, 
    select SUM(achievenum) as achieve_rows 
from games

and to display the result, you want to format it first using round:

<?php 
    echo round($completed_rate,1)."%"; 
?>

Upvotes: 5

Related Questions