-4

I'm a begginer in PHP and I want to get data from a form which contains a name,a comment and a name of a photo the user selects, and put it in a csv.But when i try to write the date, the data i already have in the csv is overwrited.So every time I only have one line in my csv with the newest data.

I want data to be introduced in a new csv line everytime the form is used like this:

Russel,Hello,Football.jpg
James,Bye,Coke.png

Instead of being overwrited like this:

James,Bye,Coke,png

This is what i tried:

if (isset($_POST['submit'])) {
    $name = $_POST["nom"];
    $comment = $_POST['com'];
    $image = $_FILES['imag']['name'];
    $csvfile = 'fichero.csv';
    $fvisitas = fopen($csvfile, "c+");
    $lista = array(
       array($name, $comment, $image)
    );
    foreach ($lista as $campos) {
        fputcsv($fvisitas, $campos);
    }
    fclose($fvisitas);
}
AD7six
  • 63,116
  • 12
  • 91
  • 123
Reyes29
  • 1
  • 3
  • 1
    You are creating the file every time you open it with the second parameter: "c+" - replace this with an "a" and data is appended to the file. For reference: https://www.php.net/manual/de/function.fopen.php -> have a look at the section "mode". – aurora Nov 10 '22 at 16:50
  • If you have a new question - please ask a new question. It is not helpful or respectful to the people who took the time to read and answer the asked question to have the question changed significantly. – AD7six Nov 10 '22 at 18:27

2 Answers2

0

You should open your file with the append flag

  $fvisitas = fopen($csvfile, "a");

This will let you append lines instead.

0

You should use a+ mode.

For more about fopen modes refer to fopen

$fvisitas = fopen($csvfile, "a+");
anaconda
  • 1,065
  • 10
  • 20