按零警告排除故障

时间:2012-05-31 05:50:12

标签: php

我希望显示与计数相似而不同的投票。我的代码如下所示,但它在filename.php中显示警告:除零。

<?php
include("db.php");

if($_POST['id'])
{
$id=mysql_escape_String($_POST['id']);
$name=mysql_escape_String($_POST['name']);

mysql_query("update messages set $name=$name+1 where id='$id'");

$result=mysql_query("select up,down from messages where id='$id'");
$row=mysql_fetch_array($result);

$up_value=$row['up'];
$down_value=$row['down'];
$total=$up_value+$down_value;

$up_per=($up_value*100)/$total;
$down_per=($down_value*100)/$total;
?>
<div style="margin-bottom:10px">
<b>Ratings for this blog</b> ( <?php echo $total; ?> total)
</div>
<table width="700px">

<tr>
<td width="30px"></td>
<td width="60px"><?php echo $up_value; ?></td>
<td width="600px"><div id="greebar" style="width:<?php echo $up_per; ?>%"></div></td>
</tr>

<tr>
<td width="30px"></td>
<td width="60px"><?php echo $down_value; ?></td>
<td width="600px"><div id="redbar" style="width:<?php echo $down_per; ?>%"></div></td>
</tr>

</table>

<?php
}
?>

3 个答案:

答案 0 :(得分:0)

在使用除法运算之前检查变量$total

e.g。 if ($total != 0)然后进行分组操作

答案 1 :(得分:0)

如果资源尚未进行投票或投票,则会导致除以零:

$up_per=($up_value*100)/$total;

答案 2 :(得分:0)

if ($total !== 0) {
  $up_per = ($up_value*100)/$total;
  $down_per = ($down_value*100)/$total;
} else {
  // what do you want to show when there is no votes.
  $up_per = 0;
  $down_per = 0;
}