简体   繁体   中英

Calculating Percentage of total value

OK I want to find out what percentage of the total rows were correct ( result=1 ) result 2 means its still active so only want the total amount of rows where result != 2

I have the following code however nothing is displayed What am I doing wrong ( am still half alseep in fairness )

$successq = mysqli_query($con,"SELECT COUNT(*) FROM `table` 
WHERE `result` ='1'");

$success = mysqli_fetch_assoc($successq);

$totalq = mysqli_query($con,"SELECT COUNT(*) FROM `table` 
WHERE `result` !='2'");

$total = mysqli_fetch_assoc($totalq);

$percent = ($success/$total) * 100;

You need to add alias for COUNT(*) and then you need to use that alias to get the values.

You need to echo your final output.

Do like below:-

$successq = mysqli_query($con,"SELECT COUNT(*) as success FROM `table` 
WHERE `result` ='1'");//success used as alias

$success = mysqli_fetch_assoc($successq);

$totalq = mysqli_query($con,"SELECT COUNT(*) as total FROM `table` 
WHERE `result` !='2'");// total use as alias

$total = mysqli_fetch_assoc($totalq);


echo $percent = ($success['success'] /$total['total'] ) * 100;// use aliases and echo the output

Note:- mysqli_fetch_assoc() return associative array, so you can't use it as a variable. You have to use it's associative indexes to fetch values from it (as i did in echo $percent = ($success['success'] /$total['total'] ) * 100; ).

Because mysqli_fetch_assoc return array not single value. So change your code as below:

$successq = mysqli_query($con,"SELECT COUNT(*) as total FROM `table` 
WHERE `result` ='1'");
$success = mysqli_fetch_assoc($successq);
$success_cnt = $success["total"];
$totalq = mysqli_query($con,"SELECT COUNT(*) as total FROM `table` 
WHERE `result` !='2'");
$total = mysqli_fetch_assoc($totalq);
$total_cnt = $total["total"];
$percent = ($success_cnt /$total_cnt ) * 100;

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