2012-09-24 65 views
0

我正在嘗試爲網站編寫一個非常簡單的PHP投票系統。基本上,選票會記錄在一個有3行的文本文件中。每一行只是一個數字。沒有任何選票的投票文件看起來像:
PHP數組寫入錯誤

0 
0 
0 

下面是我使用的PHP:

$file = "votes.txt"; 
$votes = file($file); 
$votes[0] = intval($votes[0]) + 1; 
$voteWrite = strval($votes[0]) . "\n" . strval($votes[1]) . "\n" . strval($votes[2]); 
file_put_contents($file, $voteWrite); 

所以數組保存的文本文件的每一行,如果這是代碼對第一個選項進行投票時,該行的值增加1,然後整個數組在連接成一個字符串後寫回文件,保留數組的行。理想情況下,文本文件,現在將改爲:

1 
0 
0 

但是,相反它讀取:

10 
0 

有人能告訴我這是爲什麼? PHP真的不想和我一起工作... 謝謝。

編輯:

我真的不明白這個文件()的東西......這是一個測試我設置:

$file = "votes.txt"; 
$votes = file($file); 
$option1 = $votes[0]; 
$option2 = $votes[1]; 
$option3 = $votes[2]; 

其次,在JavaScript:

alert(<?php echo $option1; ?>); 
alert(<?php echo $option2; ?>); 
alert(<?php echo $option3; ?>); 

使用文本文件分別在3行中讀取28,3和49。警報返回「28」,「450」和「未定義」。我勒個去?

+0

爲什麼你不使用數據庫? – Petah

+0

你的'file()'命令後面顯示'var_dump($ votes)'是什麼?你的文件是否被正確讀取?此外,你在那裏有一個基本的競爭條件,並會在某個時候失去投票。 –

+0

該網站正在通過大學服務器託管,並與大學合作以獲取網站上託管的數據庫是一場噩夢。 – cachgill

回答

0

像這樣的東西可能會有所幫助:

// Define the whole path of where the file is 
$fileName = '/var/home/votes/votes.txt'; 

// Check if the file exists - if not create it 
if (!file_exists($fileName)) 
{ 
    $data = array('0', '0', '0'); 
    $line = implode("\n", $data); 
    file_put_contents($line, $fileName); 
} 

// The file exists so read it 
$votes = file($fileName); 

// What happens if the file does not return 3 lines? 
$vote_one = isset($votes[0]) ? intval($votes[0]) : 0; 
$vote_two = isset($votes[1]) ? intval($votes[1]) : 0; 
$vote_three = isset($votes[2]) ? intval($votes[2]) : 0; 

$vote_one++; 

$line = "{$vote_one}\n{$vote_two}\n{$vote_three}"; 
file_put_contents($line, $fileName); 

我沒有做太多以外除去str_val並把一些錯誤檢查。試試看,它可能會更好。

如果您選擇與此不同的存儲方法,可能會好很多。稍微改變格式將爲未來提供更多的靈活性,但這個決定取決於你,它取決於你的限制條件。

使用諸如json_encodejson_decode之類的東西,將允許您在文件中存儲結構化的數據,並像以前一樣檢索它,並且它是UTF8安全的。

所以,你應該選擇去這條路線,你的代碼就變成了:

// Define the whole path of where the file is 
$fileName = '/var/home/votes/votes.txt'; 

// Check if the file exists - if not create it 
if (!file_exists($fileName)) 
{ 
    $data = array('0', '0', '0'); 
    $line = json_encode($data); 
    file_put_contents($line, $fileName); 
} 

// The file exists so read it 
$line = file_get_contents($fileName); 
$data = json_decode($line, TRUE); 

$data[0] = intval($data[0]) + 1; 

$line = json_encode($data); 
file_put_contents($line, $fileName); 

json_decode需要TRUE作爲第二個參數,從而對數據進行解碼時,創建關聯數組。

HTH

0

有沒有什麼不能存儲的信息作爲一個序列化數組的原因嗎?如果沒有,你可能要考慮這個解決方案:

$file = "votes.txt"; 
$votes = file_get_contents($file); 
$votes = $votes ? unserialize($votes) : array(0,0,0); 

$votes[0] += 1; 

file_put_contents($file, serialize($votes)); 

如果你打算重用在其他語言或用於其他目的這個文件,我認爲JSON的建議是一個很好的,甚至乾脆將值存儲用逗號分隔,如CSV。

至於爲什麼你的例子不工作:我不完全確定。零和線條結束的解釋有時可能會古怪。我不知道這些零值是否會在某處拋出PHP,可能會將一行解釋爲空?你可能會想嘗試啓動votes.txt文件看起來像:

1  
1 
1 

看它是否仍然表現的方式。

0

好吧,奇怪的數字是因爲沒有在數組值中使用intval(),並使用@file_put_contents而不是file_put_contents ...但是我無法沿着這條路走下去,我認爲前方遠遠不夠,PHP將無法滿足我的需求。