PHP& MySQL投票计数问题?

时间:2009-12-11 16:40:11

标签: php mysql

我在about.com上发现了这个脚本,我正在尝试学习如何创建一个评级系统,但是由于某种原因,脚本在点击链接并且只是重新加载页面时不会计算投票。

我想知道如何解决这个问题?我需要改变哪些代码以及在哪里?

以下是完整的脚本。

<?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>";
  } else {
        //Otherwise, we set a cooking telling us they have now voted
    $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
  if($ratings['total'] > 0 && $ratings['votes'] > 0) {
    $current = $ratings['total'] / $ratings['votes'];
  } else {
    $current = 0;
  }

  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=?mode=vote&voted=1&id=".$ratings['id'].">Vote 1</a> | ";
  echo "<a href=?mode=vote&voted=2&id=".$ratings['id'].">Vote 2</a> | ";
  echo "<a href=?mode=vote&voted=3&id=".$ratings['id'].">Vote 3</a> | ";
  echo "<a href=?mode=vote&voted=4&id=".$ratings['id'].">Vote 4</a> | ";
  echo "<a href=?mode=vote&voted=5&id=".$ratings['id'].">Vote 5</a><p>";
}
?>

2 个答案:

答案 0 :(得分:3)

永远不会设置

$mode?虽然如果register globals处于启用状态可能有效,但默认情况下它不再启用(并且在以后的PHP版本中删除)

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

也许你的意思是

if ( $_GET['mode']=="vote") {

同样适用于$id$voted,它们也从未设置过。

修改
我还想补充一点,如果我把ID改为1';DROP TABLE vote;你会丢失很多数据。看SQL Injection

修改
如果表中的行不存在,则需要先插入它才能更新它。

答案 1 :(得分:-2)

我还可以看到$ cookie永远不会被设置,查看代码应该是'Mysite'。 $ ID 即可。我添加了字符串的引号,虽然PHP会将任何未加引号的文本视为字符串,但以后会避免误解和错误,这总是一个好主意。

此脚本假设PHP选项register_globals已启用,您需要在php.ini中使register_globals = ON