Calling php function through a form

Asked

Viewed 3,176 times

0

Good afternoon, I am trying to create a page on my site is wordpress in which the user chooses a file and this file updates a table in the database.

I got code down, but when I click to load data, nothing happens. Function is not being called.

<div style="width: 50%;margin: 20px auto; ">
   <form action="" method="POST">
    Selecione o arquivo desejado:
    <select>
      <option value="" selected="selected">-----</option>
      <?php 
         foreach(glob('files/*') as 
           $filename){
           $filename = basename($filename);
           echo "<option value='" . $filename . "'>".$filename."</option>";
         }
      ?>
    </select> 
   <input type='submit' value='Carregar dados'>
</form>
</div>

<?php

if(isset($_POST)){         
 function insere() {
    echo $filename;
    echo "apagando dados da tabela...<br>"; 
    $delete = $wpdb->query("TRUNCATE TABLE `i_renda`");

    $ler=file("files/".$filename);

    foreach($ler as $linha) {
        $dados=explode(';',$linha); 
        list($nome, $cpf, $nascimento, $valor, $ano_vigencia)=$dados; 

        $wpdb->query("INSERT INTO i_renda (nome, cpf, nascimento, valor, ano_vigencia) VALUES ('".utf8_encode($nome)."', '$cpf', '$nascimento', '$valor', '$ano_vigencia')"  );
    } 
    echo "Dados incluidos com sucesso!"; exit;
    }       
    }
   ?>
  • Voce wants to insert what was selected on this page on another page ? or only that it communicates with another page at the time of Submit ?

  • You’re not calling her at any time on this page you sent, there you just created, call after creation

  • Victor, my idea is that everything happens on the same page. The user selects the file and clicks to load in the database. In this case, the form function is only to select the file and pass this parameter to the PHP function that will insert the data in the database.

  • arllondias, it’s true. I added the function call inside if. But another error occurred. It is running the function when loading the page, before the user chooses the file and click the button.

  • This one of yours if(isset($_POST)){ works? here with me does not work, ie, enters the if without submitting the form.

2 answers

2


<?php
  function insere() {
     ...........
     ...........
  }

 //ao submeter o formulário chame a função
 if(isset($_POST['submit'])){
    insere();      
 }

Put a name on the Submit button

<input type='submit' name="submit" value='Carregar dados'>

It would not be enough to use only the if condition to execute the code?

<?php
if(isset($_POST['submit'])){
    echo $filename;
    echo "apagando dados da tabela...<br>"; 
    $delete = $wpdb->query("TRUNCATE TABLE `i_renda`");

    $ler=file("files/".$filename);

    foreach($ler as $linha) {
        $dados=explode(';',$linha); 
        list($nome, $cpf, $nascimento, $valor, $ano_vigencia)=$dados; 

        $wpdb->query("INSERT INTO i_renda (nome, cpf, nascimento, valor, ano_vigencia) VALUES ('".utf8_encode($nome)."', '$cpf', '$nascimento', '$valor', '$ano_vigencia')"  );
    } 
    echo "Dados incluidos com sucesso!"; 
    exit;     
}
?>

According to the comment "se eu der f5, ele passa direito e executa direto a função", we have to, for example in Google, when refreshing the page, appears the dialog box A página que você está procurando usou as informações inseridas. Voltar à essa página poderá fazer com que todas as ações realizadas antes sejam repetidas. Deseja continuar? then click on cancelar there will be no new Sert, however, to avoid repeated data entry in the database, see how to do this post How not to write duplicate data to Mysql with PHP

  • Hi Leo, it worked. But it only works the first time q I load the page, if I give F5, it passes right and runs straight the function. As if once clicked on Ubmit, it was always active.

  • @Nathalianegram, "se der f5,, temos que, por exemplo no Google, surge a caixa de dialogo The page you are looking for used the entered information. Going back to this page can cause all actions performed before to be repeated. Continue?daí se clicar emcancel` there will be no new Insert, however, to avoid inserting repeated data into the database, see how in this post https://answall.com/questions/10744/como-n%C3%A3o-record-duplicate-data-in-mysql-with-php

  • I found a solution on this Question: https://stackoverflow.com/questions/5690541/best-way-to-avoid-the-submit-due-to-a-refresh-of-the-page echo at the end, I put a header('Location: ../enviado');

0

Final solution:

<div style="width: 50%;margin: 20px auto; ">

 <form action="" method="POST">
  Selecione o arquivo desejado:
  <select name="file">
    <option value="" selected="selected">-----</option>
    <?php 
       foreach(glob('files/*') as $filename){
         $filename = basename($filename);
         echo "<option value='" . $filename . "'>".$filename."</option>";
       }
    ?>
  </select> 
  <input type='submit' value='Carregar dados' name='submit'>
 </form>
</div>

<?php  
 if(isset($_POST['submit'])){  
   $filename = $_POST['file'];
   $delete = $wpdb->query("TRUNCATE TABLE `i_renda`");
   $ler=file("files/".$filename);
   foreach($ler as $linha) {
    $dados=explode(';',$linha); 
    list($nome, $cpf, $nascimento, $valor, $ano_vigencia)=$dados; 
    $wpdb->query("INSERT INTO i_renda (nome, cpf, nascimento, valor, ano_vigencia) VALUES ('".utf8_encode($nome)."', '$cpf', '$nascimento', '$valor', '$ano_vigencia')"  );
   }
   header('Location: ../enviado');
   exit;            
 }
?>

Browser other questions tagged

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