简体   繁体   English

foreach语句和设置变量以在循环外使用

[英]foreach statements and setting variables to use outside of loop

I have created a foreach statement that will access a MySQL database and will display the Username and ID of each person in the database in a list -- no problem there. 我创建了一个foreach语句,该语句将访问MySQL数据库,并将在列表中显示数据库中每个人的用户名和ID-那里没有问题。 The button next to each person will display the ID number -- no problem there. 每个人旁边的按钮将显示ID号-在那里没有问题。 However when I press the button it will return the value of the very last person which in this case is 30 rather than the number 1 or whatever number of the button I press. 但是,当我按下按钮时,它将返回最后一个人的值,在这种情况下为30,而不是数字1或我按下的任何数字。

I think this is because as the page is displayed it assigns the ID to the variable for each pass of the loop as it is being displayed. 我认为这是因为在显示页面时,它会为循环的每个遍历将ID分配给变量。

$ID will be set to the last one because on displaying the page it goes through everyone in the list before finishing off at the last option, just in displaying the page. $ID将被设置为最后一个,因为在显示页面时,它会遍历列表中的每个人,然后在最后一个选项(显示页面)中结束。 So when it comes to me pressing the button of course $ID will be set to 30, because it had to count up to that just so I can see it. 因此,当涉及到我时,当然将$ID的按钮设置为30,因为它必须累加起来才可以看到它。 That is the problem I'm having. 那就是我的问题。 When I press the button I want the Session['id'] to be set to what ever the $ID is set to then, not what the $ID is set to after the page has finished displaying. 当我按下按钮时,我希望将Session['id']设置为$ID所设置的值,而不是页面完成显示后将$ID设置为的值。

<?php
include 'connect.php';

foreach($db->query("SELECT * FROM Staff") as $row) {
    $ID = $row['id']
    Echo $row['id'];
    Echo $row['FirstName'];
    Echo $row['LastName'];
?> 


<button Class="link" id="OpenUp"><?php echo $id; $_SESSON['id'] = $id; ?></button>
<?php } ?>

Your code will always set $_SESSION['id'] to your last value. 您的代码将始终将$ _SESSION ['id']设置为最后一个值。

You can start a form before the loop and use this bit of code instead of button 您可以在循环之前启动表单,并使用此代码段代替按钮

<input type="submit" name="setsessionid" value="<?php echo $row['id']; ?>" />

After that all you have to do is set the variable as $_SESSION['id'] using 之后,您要做的就是使用以下命令将变量设置为$ _SESSION ['id']

<?php if(isset($_POST['setsessionid']) { $_SESSION['id'] = $_POST['setsessionid']; } ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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