2009-12-11 93 views
-1

我在about.com上發現了這個腳本,我試圖從中學習如何創建評分系統,但由於某種原因,當鏈接被點擊並重新加載頁面時,腳本不會計數投票。PHP和MySQL票數問題?

我想知道如何解決這個問題?我需要更改哪部分代碼以及在哪裏?

下面是完整的腳本。

<?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>"; 
} 
?> 
+0

你一票下來濫用這個網站上,你已經將這些代碼一次,一小時前你創造了這個問題。如果你想改變你的問題的一些細節,編輯原來的問題,不要問一個新的問題,你只是重複自己。 – TravisO 2009-12-11 18:11:31

回答

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

編輯
如果表中的行不存在,則需要將其插入,然後才能對其進行更新。

+0

這不會工作。 – PeAk 2009-12-11 16:49:54

+1

請澄清爲什麼? – Yacoby 2009-12-11 16:51:44

+0

它不會計票。它只是說你的投票已經投了。 – PeAk 2009-12-11 16:53:31

-2

我也可以看到$ cookie從來沒有設置,看代碼應該是'Mysite'。 $ id。我爲字符串添加了引號,但PHP會將任何未加引號的文本視爲字符串,但後來避免誤解和錯誤,它總是一個好主意。

而且這個腳本假定PHP選項register_globals的是,你需要做的是register_globals = on的在php.ini

+3

永遠不要打開register_globals,有人應該拿走你的服務器甚至提出這個建議。 – TravisO 2009-12-11 18:09:52