gpt4 book ai didi

PHP/MySQL - 在更正 PHP 警告方面需要帮助?

转载 作者:太空宇宙 更新时间:2023-11-03 11:19:50 25 4
gpt4 key购买 nike

我在 about.com 上找到了这个脚本,我正试图从中学习如何创建评级系统,但该脚本给了我一个警告,我在下面列出了这一点。

我想知道如何解决这个问题?我需要更改代码的哪一部分以及在哪里?

下面是警告。

Warning: Division by zero on line 43

这是下面的脚本。

<?php
// Connects to your Database
mysql_connect("localhost", "root", "", "sitename") or die(mysql_error());
mysql_select_db("sitename") 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 vote SET total = total+$voted, votes = votes+1 WHERE id = $id");
Echo "Your vote has been cast <p>";
}
}



//Puts SQL Data into an array
$data = mysql_query("SELECT * FROM vote") 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['name']."<br>";

//This calculates the sites ranking and then outputs it - rounded to 1 decimal
$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[id].">Vote 1</a> | ";
Echo "<a href=".$_SERVER['PHP_SELF']."?mode=vote&voted=2&id=".$ratings[id].">Vote 2</a> | ";
Echo "<a href=".$_SERVER['PHP_SELF']."?mode=vote&voted=3&id=".$ratings[id].">Vote 3</a> | ";
Echo "<a href=".$_SERVER['PHP_SELF']."?mode=vote&voted=4&id=".$ratings[id].">Vote 4</a> | ";
Echo "<a href=".$_SERVER['PHP_SELF']."?mode=vote&voted=5&id=".$ratings[id].">Vote 5</a><p>";
}
?>

最佳答案

您需要确保您没有使用 0 进行除法。如果您从 MySQL 获得的 totalvotes 的值为 0,您应该绕过除法并设置一个固定值。

//This calculates the sites ranking and then outputs it - rounded to 1 decimal
if($ratings['total'] > 0 && $ratings['votes'] > 0) {
$current = $ratings['total'] / $ratings['votes'];
}
else{
$current = 0;
}

附言
请注意我是如何引用 $ratings 数组中的元素的。您应该始终这样做。

// This is INCORRECT. Causes error notices if you have error reporting on.
// and can have other consequences if you happen to use a `total` constant.
$ratings[total];

// It should be
$ratings['total']

关于PHP/MySQL - 在更正 PHP 警告方面需要帮助?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1888591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com