划分零错误投票

时间:2014-03-22 15:40:07

标签: php

我正在尝试实现一个投票系统,当用户点击页面刷新的一个超链接并且数据库应该用数据库信息更新时,我得到了一个除零错误,这不再是由于包含条件语句,但是当用户单击其中一个超链接时,投票不起作用并且数据库不会更新。

<?php 
 // Connects to your Database 
 mysql_connect("localhost", "root", "password") or die(mysql_error()); 
 mysql_select_db("dbname") or die(mysql_error()); 

  //We only run this code if the user has just clicked a voting link
 if ( $mode=="vote") 
 { 

 //If the user has already voted on the particular thing, we do not allow them to vote again    

 $cookie = "Mysite$id"; 
 if(isset($_COOKIE[$cookie])) 
    { 
    Echo "Sorry You have already ranked that site <p>"; 
    } 

  //Otherwise, we set a cooking telling us they have now voted 
else 
    { 
    $month = 2592000 + time(); 
    setcookie(Mysite.$id, Voted, $month); 

     //Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating 
 mysql_query ("UPDATE reports SET total = total + $voted, votes = votes + 1 WHERE reportID = $id"); 
    Echo "Your vote has been cast <p>"; 
    } 
 } 

 //Puts SQL Data into an array
 $data = mysql_query("SELECT * FROM reports WHERE reportID = $id") or die(mysql_error()); 

 //Now we loop through all the data 
 while($ratings = mysql_fetch_array( $data )) 
 { 

 //This outputs the sites name 
 Echo "Name: " .$ratings['reportName']."<br>"; 

  //This calculates the sites ranking and then outputs it - rounded to 1 decimal 


if(isset($ratings['votes']) && $ratings['votes'] != 0){
  $current = $ratings['total'] / $ratings['votes']; 
  Echo "Current Rating: " . round($current, 1) . "<br>"; 
}



 //This creates 5 links to vote a 1, 2, 3, 4, or 5 rating for each particular item 
 Echo "Rank Me: "; 
 Echo "<a href=".$_SERVER['PHP_SELF']."?mode=vote&voted=1&id=".$ratings['reportID'].">Vote 1</a> | "; 
 Echo "<a href=".$_SERVER['PHP_SELF']."?mode=vote&voted=2&id=".$ratings['reportID'].">Vote 2</a> | "; 
 Echo "<a href=".$_SERVER['PHP_SELF']."?mode=vote&voted=3&id=".$ratings['reportID'].">Vote 3</a> | "; 
 Echo "<a href=".$_SERVER['PHP_SELF']."?mode=vote&voted=4&id=".$ratings['reportID'].">Vote 4</a> | "; 
 Echo "<a href=".$_SERVER['PHP_SELF']."?mode=vote&voted=5&id=".$ratings['reportID'].">Vote 5</a><p>"; 
 } 
 ?>

非常感谢任何帮助

由于

1 个答案:

答案 0 :(得分:4)

在进行除法运算之前先检查$ratings[votes]的值。

if(isset($ratings[votes]) && $ratings[votes] != 0){
    $current = $ratings[total] / $ratings[votes]; 
    Echo "Current Rating: " . round($current, 1) . "<br>"; 
}