Form with fopen/fwrite

If I write fopen in every “if”, it opens itself anew and overwrite itself till the last “if”.
I wanted to loop fopen once, but this didnt worked too.
I sit with this problem 2 days and didnt got any new information for my problem. Maybe no one uses .csv for storing data.

The code:

for($i = 0;$i < 1; $i++){

$f1 = fopen("Datenbank.csv", "w");
if (!empty($_POST['vname'])) {
    $f1 = fwrite($f1, ($_POST['vname']));
} elseif (isset($_POST['vname'])) {
    echo "Bitte geben Sie ihren Vornamen ein.<br>";
}

if (!empty($_POST['nname'])) {
    $f1 = fwrite($f1, ($_POST['nname']));
} elseif (isset($_POST['nname'])) {
    echo "Bitte geben Sie ihren Nachnamen ein.<br>";
}

if (!empty($_POST['bday'])) {
    fwrite($f1, ($_POST['bday']));
} elseif (isset($_POST['bday'])) {
    echo "Bitte geben Sie ein gültiges Geburtsdatum ein.<br>";
}

if (!empty($_POST['email'])) {
    fwrite($f1, ($_POST['email']));
} elseif (isset($_POST['email'])) {
    echo "Bitte geben Sie eine gültige Email-Adresse ein.<br>";
}

fclose($f1);

}

If my english is not good enough, im sorry 🙁
Im from germany and just begun to work at a company.
They teache me to code aswell.

Try to open your file before your loop :

$f1 = fopen("Datenbank.csv", "w");
for ($i = 0; $i < 1; $i++) {
    if (!empty($_POST['vname'])) {
        $f1 = fwrite($f1, ($_POST['vname']));
    } elseif (isset($_POST['vname'])) {
        echo "Bitte geben Sie ihren Vornamen ein.<br>";
    }

    if (!empty($_POST['nname'])) {
        $f1 = fwrite($f1, ($_POST['nname']));
    } elseif (isset($_POST['nname'])) {
        echo "Bitte geben Sie ihren Nachnamen ein.<br>";
    }

    if (!empty($_POST['bday'])) {
        fwrite($f1, ($_POST['bday']));
    } elseif (isset($_POST['bday'])) {
        echo "Bitte geben Sie ein gültiges Geburtsdatum ein.<br>";
    }

    if (!empty($_POST['email'])) {
        fwrite($f1, ($_POST['email']));
    } elseif (isset($_POST['email'])) {
        echo "Bitte geben Sie eine gültige Email-Adresse ein.<br>";
    }
}
fclose($f1);

If you need to append datas to the file, you have to open the file with the “a” flag (for append) :

$f1 = fopen("Datenbank.csv", "a");

if it’s still does not work, try to check if you have the permissions to create the file :

$f1 = fopen("Datenbank.csv", "w");
if(! $f1) {
    die('Unable to create file Datenbank.csv');
}