How to run a function from a url?

Asked

Viewed 1,211 times

2

If I leave the code just below loose inside the file funcoes.php from my system, when the page reloads, it delete the post that I had deleted.

  $tipo   = $_GET['tipo'];
  $funcao = $_GET['funcao']; 

  if($_GET['tipo'] == 'blog' && $_GET['funcao'] == 'excluir'){

    require("classes/Database.php");
    $pdo  = Database::connect();
    $pdo->query("DELETE FROM tb_blog WHERE ID = ".$_GET['id']."");

    echo "
    <META HTTP-EQUIV=REFRESH CONTENT = '0;URL='>
    <script type=\"text/javascript\">
      window.location = \"index\";
    </script>
    "; 

  }

Now if I put that code inside a function, doesn’t work.

  function excluirDados(){
    $tipo   = $_GET['tipo'];
    $funcao = $_GET['funcao']; 

    if($_GET['tipo'] == 'blog' && $_GET['funcao'] == 'excluir'){

      require("classes/Database.php");
      $pdo  = Database::connect();
      $pdo->query("DELETE FROM tb_blog WHERE ID = ".$_GET['id']."");

      echo "
      <META HTTP-EQUIV=REFRESH CONTENT = '0;URL='>
      <script type=\"text/javascript\">
        window.location = \"index\";
      </script>
      "; 

    }  
  }

Question: Because the same code but inside a function does not work equal to the loose code inside the file?

I’m passing this url: .../index&tipo=blog&funcao=excluir&id=40

  • first that its function is already wrong right, it should be something like function excluirDados() {} or only function excluir(){}

  • Corrected !!! :)

  • and when you pass this data to the index or some controller, when you call the deleted function()?

  • When I send the Erase, it does Reload on the page and gives include in the file php functions.

  • 2

    until you are including the file, it does not mean that you are running the function. At some point you need to make the call of the function deletedDados(), before it was working by being out of a function, now that you put inside the function need to make a call of the same and not only include the file, understood?

  • Is there an error? Undefined index or something?

  • 1

    @rray without errors ... Marcelo, really I was not calling the function.

Show 2 more comments

1 answer

2

You can try like this:

require("classes/Database.php"); /* requiro fora da função */
function excluirDados(){
    $tipo   = $_GET['tipo'];
    $funcao = $_GET['funcao']; 

    if($_GET['tipo'] == 'blog' && $_GET['funcao'] == 'excluir'){


      $pdo  = Database::connect();
      $pdo->query("DELETE FROM tb_blog WHERE ID = ".$_GET['id']."");

      echo "
      <META HTTP-EQUIV=REFRESH CONTENT = '0;URL='>
      <script type=\"text/javascript\">
        window.location = \"index\";
      </script>
      "; 

    }  
  }
excluirDados(); /* chamar a função (no seu exemplo ela não estava sendo chamada */

Browser other questions tagged

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