Remove line from a CSV by position - PHP [duplicate]

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 delete any line he wanted by that number, I'm trying to do it through an input, where he types the line number and clicks the "delete" button. What I can not do is that from the click of the button only one line (which has the same value entered by the user) is deleted, the code is deleting all of them. Follow the code I have so far.

// CSV form and creation

<!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><scriptsrc="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><scripttype="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 PivotTable

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

// Ajax when you click the 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);
}
?>
    
asked by anonymous 23.08.2018 / 22:22

2 answers

0

In your php file do not count the lines of the file, already deal in 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 delete property.

  

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");
        }
    });
  });
});

And, with that, it will work;)

    
24.08.2018 / 12:56
-1

    
23.08.2018 / 23:28