PHP - knowing which form was pressed

Asked

Viewed 213 times

-1

I need to know which form was pressed.

I’m using a get system to differentiate, but the link would be very dirty.

My code:

$mysqli = new mysqli("localhost","root","","escritor");

    if($result = $mysqli->query("SELECT * FROM pagina")){
        if($result->num_rows == 0){
            printf("Não existe nenhuma pagina");
        }else{
            while($row = $result->fetch_assoc()){ // pega as informações da linha

                // variavel dos seguidores
                $seguidores = $row["seguidores"]; // ids das pessoas que seguem a pagina
                $array = explode(',', $seguidores); // faz um explode na $seguidores
                if(in_array($userID, $array)){ // verifica se tem o id do usuario no $array
                    $btnValue = "Descurtir"; // coloca o valor do botão como Descurtir
                }else{
                    $btnValue = "Curtir"; // coloca o valor do botão como Curtir
                }
                $link = "?post=".$row['id'];
                printf("<div><form method='post' action='$link'><p>pagina-> <b>".$row['nomePagina']."</b></p> <p>descricao-> <b>".$row["descricao"]."</b></p></label><button name='btnCurtir'>".$btnValue."</button><p></p></form></div>");
            }
        }
    }

And would use

   if(isset($_POST['btnCurtir'])){
        $postID = $_GET['post'];    // ai ia aplicar o like no post com o id $postID 
    }

How can I know in which form the button was pressed to apply the like system?

1 answer

5


Just create a HIDDEN field to know the right POST, and use the same name on both buttons:

 printf("
    <div>
       <form method='post' action='$link'>
          <p>pagina-> <b>".$row['nomePagina']."</b></p>
          <p>descricao-> <b>".$row['descricao']."</b></p>

          <input type='submit' name='botao' value='Curtir'>
          <input type='submit' name='botao' value='Descurtir'>

          <input type='hidden' name='post_id' value='".$row['id']."'>
       </form>
   </div>
");

And catch with:

$postID = $_POST['post_id'];
$botao  = $_POST['botao'];

(or the name you want in the field, just adjust the name of input)

Note that I switched the BUTTON for INPUT, to simplify. The important thing is to understand the idea, and adapt to your case. I took a </label> that was left in the code too, give a review later. Line breaks were for easy reading.

Note:

If the POST go to the same page, it is unnecessary action="destino" in the <form>, suffice:

<form method='post'>

Browser other questions tagged

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