phpfileupdating

How to update files in PHP


I have some PHP function that requires the line number of a CSV file used as database. Once it has line, it navigates to the specific value that needs to be changed, changes it and rewrites the whole files. Here is my code:

<?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!";
?>

I am unable to find the problem because whenever I run the code, it outputs "updated!" just as it should but when check the file, I find it has not been updated. I do not know why, but it always remains the same! Thanks.


Solution

  • I found out what the problem was.

    $id = $_SESSION['id'];
    $uid = $_GET['p'];
    $myfile = "myfile.txt";
    
    if(update($myfile, 12, 14, "somevalue"))
    

    The line number pointed to the previous line, which made it impossible to update the first line of the file. So all I had to do was

    $line ++;