Remove a CSV line by position - PHP

Asked

Viewed 192 times

0

Hello.I have a form that generates a CSV file with the data entered by the user. The data saved in this csv is printed on the screen where a number is assigned for each line (1,2,3...). I needed the user to be able to delete any row that he wanted through this numbering, I’m trying to do through an input, where he type the line number and click the "delete" button. What I can’t do is make that from the click of the button is deleted only one line (the one that has the same value typed by the user), the code is erasing all. Follow the code I have so far.

//Form and creation of CSV

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<?php
if ($_POST){
    $nome = $_POST["nome"];
    $telephone = $_POST["telefone"];
    $cargo = $_POST["cargo"];
    $setor = $_POST["setor"];

    $quantidadeLinhas = count($nome);
    $dados = "";
    $fileName = "dados.csv"; 

    for ($i=0; $i<$quantidadeLinhas; $i++) {
      $dados .= "$nome[$i],";
      $dados .= "$telephone[$i],";
      $dados .= "$cargo[$i],";
      $dados .= "$setor[$i]";
      $dados .= "\n"; 
     } 

   $fileHandle = fopen($fileName,"a+"); 
   fwrite($fileHandle,"$dados"); 
   fclose($fileHandle);
}
?>

<html>

 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 

   <title>Formulário</title>

   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   <script src="https://rawgit.com/RobinHerbots/jquery.inputmask/3.x/dist/jquery.inputmask.bundle.js"></script>
   <script type="text/javascript" src="adiciona.js"></script>
   <script type="text/javascript" src="excluiLinha.js"></script>

   <style type="text/css" media="all">
    body{ font-family:Arial, Helvetica, sans-serif }
    #tudo{ border:#CCCCCC 1px solid;width:570px;margin:0 auto }
    .bd_titulo{
    text-align:center;
    background-color:#CCCCCC;
    font-weight:bold
     }
    </style>

  </head>

  <body>
   <form method="post" name="frm_campo_dinamico" action="">
   <div id="tudo">
  <table border="0" cellpadding="2" cellspacing="4" width="100%">
  <tr><td colspan="4" class="bd_titulo">Formulário</td></tr>
  <tr><td colspan="4" align="center"></td></tr>
     <tr>
      <td class="bd_titulo" align="center">Nome</td><td class="bd_titulo" align="center">Telefone</td><td class="bd_titulo" align="center">Cargo</td><td class="bd_titulo" align="center">Setor</td>
     </tr>
     <tr class="linhas">
       <td>
        <input style="text-align:center" align="center" type="text" name="nome[]"/>
       </td>
       <td>
        <input type="text" id = "telefone" align="center" name="telefone[]" class = "telMask"/>
       </td>
       <td>
        <select name="cargo[]">
          <option>Selecione</option>
          <option value="Auxiliar">Auxiliar</option>
          <option value="Secretária">Secretária</option>
          <option value="Gerente">Gerente</option>           
        </select>
       </td>
       <td>
        <select name="setor[]">
                 <option>Selecione</option>
                 <option value="Comercial">Comercial</option>
                 <option value="Administrativo">Administrativo</option>            
        </select>
       </td> 
      </td>
    </tr>
        <tr>
         <td colspan="4">
          <a href="#" class="adicionarCampo" title="Adicionar item"><img src="add.svg" border="0" /></a>
         </td>
        </tr>
        <tr>
         <td align="center" colspan="0">
         <td align="right" colspan="4">
         <input type="submit" id="Salvar" value="Salvar" class = "gwt-Button" />
         </td>
        </tr>
      </tr> 
    </table>
   </form>
   </div>

  <hr width="1" size="1" color = "white">

   <div id="tudo">
   <table border="0" cellpadding="2" cellspacing="4" width="100%">
   <tr><td colspan="4" class="bd_titulo">Dados Salvos</td></tr>
   <tr><td colspan="4" align="center"></td></tr>
     <tr>
      <td class="bd_titulo" align="center">Linha</td><td class="bd_titulo" align="center">Nome</td>td class="bd_titulo" align="center">Telefone</td><td class="bd_titulo" align="center">Cargo</td><td class="bd_titulo" align="center">Setor</td>
     </tr>
     <tr>
      <td align="center"><font color="black"><?php $file = fopen('dados.csv','r'); $contando = 1; while (($line = fgetcsv($file)) !== false){echo $contando++."<br />";} ?></font></td>
      <td align="center"><font color="black"><?php $file = fopen('dados.csv','r'); while (($line = fgetcsv($file)) !== false){echo $line[0]."<br />";}?></font></td>
      <td align="center"><font color="black"><?php $file = fopen('dados.csv','r'); while (($line = fgetcsv($file)) !== false){echo $line[1]."<br />";}?></font></td>
      <td align="center"><font color="black"><?php $file = fopen('dados.csv','r'); while (($line = fgetcsv($file)) !== false){echo $line[2]."<br />";}?></font></td>
      <td align="center"><font color="black"><?php $file = fopen('dados.csv','r'); while (($line = fgetcsv($file)) !== false){echo $line[3]."<br />";}?></font></td> 
    </tr>
    </table>
   </form>
   </div>

  <hr width="1" size="1" color = "white">

    <form method="post" name="salvos" action="">
   <div id="tudo">
     <table border="0" cellpadding="2" cellspacing="4" width="100%">
     <tr><td colspan="4" class="bd_titulo">Excluir Linha</td></tr>
     <tr><td colspan="4" align="center"></td></tr>
     <tr>
      <td align="center" colspan="4">
      <font color="black">Linha:</font> 
      <input style="text-align:center" type="number" min = "1" name="deletar"/>
      <input type="submit" id="btnExcluir" value="Excluir" class = "gwt-Button"/>
     </tr>
    </table>
   </form>
   </div>

 </body>

</html>

//for the dynamic table

$(function () {
$(".adicionarCampo").click(function () {
  novoCampo = $("tr.linhas:first").clone();
  novoCampo.find("input").val("");
  novoCampo.insertAfter("tr.linhas:last");
  });
});

//Ajax when click delete button

$(document).ready(function() {
  $('#btnExcluir').click(function(){
    //Pega o valor a ser excluido
    var deletar = $("deletar").val();
    $.ajax({
        type: "POST",
        url: "deletarLinhas.php",
        data: deletar,
        success: function () {
            alert("Teste se tá enviando");
        }
    });
  });
});

//PHP that will delete the line (Part that does not work)

<?php
$removerLinha = $_POST["deletar"];

$meuArray = Array();
$file = fopen("dados.csv", "r");

while (($line = fgetcsv($file)) !== false){
  $meuArray[] = $line;
}

fclose($file);

$remover = $removerLinha - 1;
$linhas = count(file("dados.csv"));
$limite = $linhas -1;

//verifica se o valor dado pelo usuário é menor ou igual ao numero de linhas do arquivo
if ($remover<=$limite){
 //remove
 unset($meuArray[$remover]);
 $meuArray = array_values($meuArray);
 //realinha
 var_dump($meuArray);
 //reescreve o arquivo sem a linha excluida
 $fileHandle = fopen("dados.csv","w"); 
 fwrite($fileHandle,$meuArray); 
 fclose($fileHandle);
}
?>
  • I do not see as duplicate because my question refers to the removal of a specific line that may be in the middle of the file, the answers given in this question are to cut the file to a certain line, not remove a.

2 answers

0


In your php file do not count the lines of the file, already deal with no for the line you want to remove.

Example

<?php

$removerLinha = $_POST["deletar"] - 1;

$meuArray = Array();
$file = fopen("dados.csv", "r");

$index = 0;
while (($line = fgetcsv($file)) !== false){
  if($index != $removerLinha) {
        $meuArray[] = implode(",", $line);
  }
  $index++;
}

fclose($file);

// apagando arquivo antigo
unlink("dados.csv");

// recriando arquivo sem a linha
   $fileHandle = fopen("dados.csv", "a+"); 
   fwrite($fileHandle, implode("\n", $meuArray)); 
   fclose($fileHandle);

And in your ajax that sends the line, remember to specify the property delete.

Example:

$(document).ready(function() {
  $('#btnExcluir').click(function(){
    //Pega o valor a ser excluido
    var deletar = $("[name=\"deletar\"]").val();
    $.ajax({
        type: "POST",
        url: "deletarLinhas.php",
        data: {deletar: deletar},
        success: function () {
            alert("Teste se tá enviando");
        }
    });
  });
});

That’s it, that’s it ;)

  • Thanks for the help. So that way it didn’t work, he wrote array on all lines of the first column of CSV. I will edit the post and put as it was, the comments have no way to fix image.

  • @Marie already put the correction

  • Now it deletes the line, as if it had 1,2,3,4 becomes 1,2,3. But the data vanishes, only the number of the line appears and the rest is blank. I don’t know what else to do :(

  • @Marie see if the implode quotation marks on the while are correct, as I wrote by the cellular... they may be wrong...

  • @Marie I set the quotes, try again.

  • Now it is doing nothing when I click the delete button. Remain the same data as before.

  • @Marie tried to erase which line?

  • @Marie the $("delete"). val() is an id? If it is missing the #

  • no, it’s like name

  • @Marie edited the answer...

  • remains the same :/

  • @Marie puts an Alert in the delete and tell me what it printed..

  • I was able to solve here. It was a problem with the browser and really the capture of the value of the number was wrong, I modified it to an ID. Thank you so much for your help, your solution came true.

  • Aee!! I’m glad it worked.

Show 9 more comments

-1

Try instead unset($meuArray[$remove]) do the following array_splice($meuArray, $remove , 1).

Browser other questions tagged

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