phpwhile-loopsubmit-button

How to isset a submit button generated in a while loop, outside the loop?


Does one of you know how to isset the submit button outside the loop?

When I isset outside the loop, the name of the button = all the id messages (thus my isset is not working)
whereas when I isset inside the loop, the name of the button = one id message (thus, inside the isset is working properly).

However, I need to isset the submit button outside the loop. Can you help me please?

$conn = new PDO("mysql:host=localhost;dbname=likes;charset=utf8", "root", "");

$resultats = $conn->prepare("SELECT * FROM message ORDER BY date DESC LIMIT 50");
$resultats->execute();

while (($messages = $resultats->fetch())!== false){ 

?>

<form action="" method="POST">
    <button type="submit" name="<?php echo $messages['idmessage']; ?>">Likes</button>
</form>

<?php
}
?> 

<?php

if(isset($_POST[$messages['idmessage']])){
echo $messages['idmessage'];
}

?> 

Solution

  • I'd include a type='hidden' for each form like so

    <form action="" method="POST">
        <input type='hidden' name='message_id' value='<?php echo $messages['idmessage']; ?>' />
        <button type="submit" name="like_button">Likes</button>
    </form>
    
    
    <?php
    if(isset($_POST['like_button'])) {
       #get the message id for the form that was submitted
       echo isset($_POST['message_id']) ? 'Message ID is '. $_POST['message_id'] : 'no message id found. Kill script';
    }
    
    ?>