verification and addition in CSV and PHP

Asked

Viewed 17 times

-2

I need my script every time I submit write a new line in my file. csv as is and does not replace the line that already exists, and also make a check if there is already a $email already registered and if there is to stop the execution and do not write anything. I’d be very grateful if you’d help me !!

$arquivo = fopen('duvidas.csv','w');
    while(true) {
    $linha = fgets($arquivo);
    if ($linha==null) break;
}
$texto = "$nome,$email,$nasc";
fwrite ($arquivo, $texto);

1 answer

-1

Use the fgetcsv of PHP: see https://www.php.net/manual/en/function.fgetcsv.php

Similar to the function fgets(), except that fgetcsv() interprets the line in CSV format and returns an array containing the read fields.

$arquivo = fopen('duvidas.csv','w');

$email_cadastrado = false;

while ( ($data = fgetcsv($handle) ) !== FALSE ) {
   if($data[1] == $email){//$data[1] é a posicao do email no seu array!?
      $email_cadastrado = true; break;
   }
}
//se o email nao estive cadastrado, insere
if(!$email_cadastrado){
   $texto = "$nome,$email,$nasc";
   fwrite ($arquivo, $texto);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.