Jump to content

Updating a Row in a CSV File


shaunie

Recommended Posts

Sorry if the answer isn't brilliant, it's my first post :D

 

Try using fopen to get the file contents and then use fgetcsv to parse the fields into an array, you can then loop through the array and change the rows for your particular id.


It may be really resource hungry but i'm an amateur myself so I'm not sure, this is just how I would go about it, the PHP manual is very handy.

Link to comment
Share on other sites

Thanks 

 

I've got this so far but for some reason I am unable to open the file for reading and writing at the same time?

 

if(isset($_POST)){
$row = 1;
if (($handle = fopen("customers.csv", "r+")) !== FALSE) {
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
       $num = count($data);
       $row++;
       for ($c=0; $c < $num; $c++) {
        echo '$data[0] = ' . $data[0];
           if($data[0] == $_POST['customerId']){
            echo 'true';
            $data[1] = $_POST['name'];
            $data[2] = $_POST['email'];
           }
       
       }
       fputcsv($handle, $data);
   }
   fclose($handle);
}
}

 

Link to comment
Share on other sites

Thank you, I have updated it so the file is closed for reading and then opened for writing, but it's still not editing the file...

if(isset($_POST)){
	$row = 1;	
	if (($handle = fopen("customers.csv", "r")) !== FALSE) {
	    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
	        $num = count($data);
	        $row++;
	        for ($c=0; $c < $num; $c++) {
	            // Customer ID exists so edit the record
	        	if($data[0] == $_POST['customerId']){
	            	$data[1] = $_POST['name'];
	            	$data[2] = $_POST['email'];	            
	            }
	       		
	        }	        
	    }
	    fclose($handle);
	}
	if (($handle = fopen("customers.csv", "w")) !== FALSE) {
		fputcsv($handle, $data);
	}
}
Link to comment
Share on other sites

the problem is your LOGIC.

 

you must open the input file for reading, open a separate new output file for writing. then as you loop through the lines from the input file, you replace/update the data if it matches the submitted post data, and you write each line (both the unchanged and the updated ones) to the output file.

Link to comment
Share on other sites

the problem is your LOGIC.

 

you must open the input file for reading, open a separate new output file for writing. then as you loop through the lines from the input file, you replace/update the data if it matches the submitted post data, and you write each line (both the unchanged and the updated ones) to the output file.

Then rename the two files, so the next time the process is run, you get the "new" file as input.

 

By the way: if there is any possibility that the page will be submitted from two different users, or even browser tabs, at the same time, you will experience data loss. This is one of the reasons that a database is recommended for data processing.

Link to comment
Share on other sites

starting with the logic in this thread - http://forums.phpfreaks.com/topic/278189-csv-class-need-help-updating-a-csv-file/?hl=%2Btempnam you would end up with something that looks like -

$csvfile = 'customers.csv';

$tempfile = tempnam(".", "tmp"); // produce a temporary file name, in the current directory

if(!$input = fopen($csvfile,'r')){
    die('could not open existing csv file');
}
if(!$output = fopen($tempfile,'w')){
    die('could not open temporary output file');
}

while(($data = fgetcsv($input)) !== FALSE){
    if($data[0] == $_POST['customerId']){
        $data[1] = $_POST['name'];
        $data[2] = $_POST['email'];
    }
    fputcsv($output,$data);
}

fclose($input);
fclose($output);

unlink($csvfile);
rename($tempfile,$csvfile);

echo 'done';

 

Link to comment
Share on other sites

Thanks guys, unfortunately the above code doesn't work, which leads me to believe there is a permissions issue. I have even commented out the lines:

 

//unlink($csvfile);
//rename($tempfile,$csvfile);
 
and the temp file is not present in that directory...
Link to comment
Share on other sites

Perhaps...

if(isset($_POST)){
    $needle = $_POST['customerId'];
    $new_line = $needle . "," . $_POST['name'] . "," . $_POST['email'];
    $lines = file("customers.csv");
    $c = count($lines);
    $i = 0;
    while($i<$c) {
     $t_array = explode(",", $lines[$i]);
     if($t_array[0] == $needle) { $lines[$i] = $new_line; }
     $new_data = $new_data . $lines[$i] . "\n";
     $i ++;
    }

    $file_handle = fopen("customers.csv", 'w');
    fwrite($file_handle, $new_data);
    fclose($file_handle);
}

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.