计算总价值的百分比

时间:2017-11-07 11:35:21

标签: php math mysqli percentage

好的我想知道总行数的百分比是正确的(结果= 1)结果2意味着它仍然有效,所以只想要结果的总行数!= 2

我有以下代码,但没有显示任何内容 我做错了什么(我公平地说仍然是一半)

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

2 个答案:

答案 0 :(得分:0)

您需要为COUNT(*)添加别名,然后您需要使用该别名来获取值。

您需要echo最终输出。

如下所示: -

$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

注意: - mysqli_fetch_assoc()返回关联数组,因此您无法将其用作变量。您必须使用它的关联索引来从中获取值(就像我在echo $percent = ($success['success'] /$total['total'] ) * 100;中所做的那样)。

答案 1 :(得分:0)

因为mysqli_fetch_assoc返回的数组不是单个值。所以改变你的代码如下:

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