简体   繁体   中英

Determining which button is clicked when the button has been created in a while loop

I've written a while loop in PHP which creates many buttons which contain their individual username in a drop-down list, which relate to some usernames being brought in from a database. (it's a friend adding system)

I would like to be able to get the username from the clicked button and just store it in a variable, I know what to do from there, but I can't work that out.

if($getAddFriendUsernamesResult)
            {
                $row=mysqli_fetch_array($getAddFriendUsernamesResult);
                while($row)
                {
                    $username = $row['username'];
                    if($username!=$_SESSION['_username']) #Doesnt print the users own name in add friends
                    {
                        ?><a><button class="AddFriendButton"><?php echo $row['username']; ?></button></a>
                        <?php   
                    }
                    $row=mysqli_fetch_array($getAddFriendUsernamesResult);
                }
            }

At the moment this lists all of the usernames accept the person logged in in a long list. I want to get the contents of the button (the username of the clicked button) and store that in a php variable.

First, get rid of the <a> tag.

Then give the button name and value attributes.

<button name="add_friend" class="AddFriendButton" value="<?= $row['username'] ?>">
    <?= echo $row['username']; ?>
</button>

Then (assuming all the code in your loop is contained in a <form> element), you'll be able to get the value from $_POST['add_friend'] .


Overall, something like this:

<?php if ($getAddFriendUsernamesResult) {

    // open a form
    echo '<form method="post" action="add_friend.php">';
    while ($row = mysqli_fetch_array($getAddFriendUsernamesResult)) {
        $username = $row['username'];
        if ($username != $_SESSION['_username']) {

            // give each button a name and value - may want to use id instead of username
            echo "<button name='add_friend' value='$row[username]' class='AddFriendButton'>
                      $row['username']
                  </button>";
        };
    }
    echo '</form>';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM