2015-04-15 51 views
2

我有一些PHP函數需要用作數據庫的CSV文件的行號。一旦它有行,它將導航到需要更改的特定值,更改它並重寫整個文件。這裏是我的代碼:「更新」如何在PHP中更新文件

<?php 
function update($file, $id, $field, $value) 
{ 
//$id is the line number 
    $contents = explode("\n", file_get_contents($file)); 
    $fh = fopen($file, "w"); 
    $lines = array(); 
    foreach($contents as $line) 
    { 
    if($line == "") 
     continue; 
    $fields = explode("|", $line); 
    if($fields[0] == $id) 
    { 
    $line = null; 
    for($i = 0; $i<count($fields); $i++) 
     { 
     if($i == $field) 
     $fields[$i] = $value; 
     if($i != count($fields)-1) 
     $line .= $fields[$i]."|"; 
     else 
     $line .= $fields[$i]; 
     } 
    } 
$line .= "\n"; 
fwrite($fh, $line); 
} 
fclose($fh); 
$contents = null; 
return true; 
} 

$id = $_SESSION['id']; 
$uid = $_GET['p']; 
$myfile = "myfile.txt"; 

if(update($myfile, 12, 14, "somevalue")) 
    echo "updated!"; 
?> 

我無法找到問題,因爲每當我運行的代碼,它輸出就像它應該但檢查文件時,我發現它沒有被更新。我不知道爲什麼,但它始終保持不變!謝謝。

回答

1

檢查fwrite()沒有失敗。

做這樣的事情:

... 
    $writeSuccess = (fwrite($fh, $line) !== false); 
} 
fclose($fh); 
$contents = null; 
return $writeSuccess; 
} 
... 

如果失敗,請檢查你的文件系統權限設置是否正確。 Apache用戶需要具有寫入文件/文件夾的權限。

+0

那麼,我已經檢查$ writeSuccess。它的值是1,這意味着它實際上是寫作。 –

0

我發現問題是什麼。

$id = $_SESSION['id']; 
$uid = $_GET['p']; 
$myfile = "myfile.txt"; 

if(update($myfile, 12, 14, "somevalue")) 

指向前一行的行號,這使得無法更新文件的第一行。所以我只需要做

$line ++;