简体   繁体   English

从POST获取动态变量

[英]Get a dynamic variable from POST

I want to randomize a number of users selected by an administrator. 我想随机化管理员选择的一些用户。

So first, I have a page that reads all the name from the "Users" table. 首先,我有一个页面,它从“Users”表中读取所有名称。 Then I display the names with a checkbox next to it so the admin can deselect names that aren't going to participate. 然后我显示名称旁边的复选框,以便管理员可以取消选择不参加的名称。

<input name="User<? echo $rows['UserID']; ?>" type="checkbox" value="1" checked/>

So, it will set values like User1 = 1; 因此,它将设置像User1 = 1的值; User2 = 0; User2 = 0; User3 = 1, and so on... User3 = 1,依此类推......

Next, I want to write to the database the users that were selected in the form so I can read that table again to randomize the participants. 接下来,我想向数据库写入在表单中选择的用户,以便我可以再次读取该表以随机化参与者。 How do I read the dynamic variable from the previous form? 如何从上一个表单中读取动态变量? I'm trying to read the variable from the POST and store it in the variable Player (ie: User1 value is stored in Player1 variable)... this but doesn't seem to work: 我正在尝试从POST读取变量并将其存储在变量Player中(即:User1值存储在Player1变量中)...这但似乎不起作用:

    $x = 1;
while ($x <= $total_records) {
    ${"Player" . $x} = $_POST[ ${"User" . $x} ];
    $x++;
    echo "Player" . $x . " = " . ${"Player" . $x} . "<BR>";
}

The result is "Player1 = ", "Player2 = ". 结果是“Player1 =”,“Player2 =”。 Always empty. 永远是空的。

Any idea, or an easier way to do it? 有什么想法,或者更简单的方法吗? ;) Thanks! ;) 谢谢!

I would recommend a separate approach. 我会建议一个单独的方法。 Instead of creating a different name for each checkbox, how about making them an array and their values are the users' ids? 而不是为每个复选框创建不同的名称,如何使它们成为一个数组,它们的值是用户的ID?

For instance: 例如:

<input type="checkbox" name="User[]" value="<? echo $rows['UserID']; ?>" />

Then, you'll only have to iterate over the submitted array: 然后,您只需要遍历提交的数组:

if (isset($_POST['User']) && is_array($_POST['User'])) {
    foreach ($_POST['User'] as $userId) {
        // do something with the user id!
    }
}

If you want to keep the list as, well, a "list" to be reused, you could implode() the array that's posted and explode() when you need to use it again: 如果你想保持列表,以及一个要重用的“列表”,当你需要再次使用它时,你可以内implode()发布的数组和explode()

$combinedIds = implode(',', $_POST['User']);
// now you have 1,3,17

$splitIds = explode(',', $combinedIds);
// now you have array(1, 3, 17)

You can store the list in the db, a session variable, etc. If you store in a session variable, you could also directly store the array (whichever's easier =P). 您可以将列表存储在db,会话变量等中。如果存储在会话变量中,也可以直接存储数组(以更简单的方式为P)。

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

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