[英]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. 我在PHP中编写了一个while循环,该循环创建了许多按钮,这些按钮在下拉列表中包含各自的用户名,这与从数据库引入的某些用户名有关。 (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. 我想获取按钮的内容(单击按钮的用户名)并将其存储在php变量中。
First, get rid of the <a>
tag. 首先,摆脱<a>
标记。
Then give the button name
and value
attributes. 然后提供按钮name
和value
属性。
<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']
. 然后(假设循环中的所有代码都包含在<form>
元素中),您将可以从$_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>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.