doukuang1897 2019-07-03 20:51
浏览 181
已采纳

有没有办法在循环中获取$ _POST变量?

Is there a way to make a loop that would give me this, depending on the number of users I want to grab?

$user1 = htmlentities($_POST['user1']);
$user2 = htmlentities($_POST['user2']);
$user3 = htmlentities($_POST['user3']);

I've tried this:

while ($i <= $useramm) {
    ${"user$i"} = htmlentities($_POST['user-' + $i]);
    $i=$i+1;
}

but it shows me these errors:

Warning: A non-numeric value encountered in C:\xampp\htdocs\test.php on line 14 Notice: Undefined offset: 1 in C:\xampp\htdocs\test.php on line 14

  • 写回答

1条回答 默认 最新

  • duanfei8897 2019-07-03 21:03
    关注

    Yes, you could do this with variable variables, but you need to use concatenation operator instead of addition.

    $i = 0;
    while (++$i <= $useramm) {
        ${"user$i"} = htmlentities($_POST['user' . $i]);
    }
    

    A better way would be to use an array. Instead of numbering your field user1, user2 and so on, just use array.

    In your HTML define POST fields as the same name with [] at the end. PHP will parse this as an array with key user:

    <form method="POST">
        <input type="text" name="user[]" />
        <input type="text" name="user[]" />
        <input type="text" name="user[]" />
        <input type="text" name="user[]" />
        <input type="submit" value="submit">
    </form>
    

    Then in PHP you can just use the array values, either in a loop or directly accesing through an index.

    foreach ($_POST['user'] as $singleUser) {
        // use $singleUser here
    }
    // or 
    $_POST['user'][0]; // first user field
    $_POST['user'][1]; // second user field
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有偿求qftp工具。能连接,下载文件,发送代码,windows环境,最好qt6 要qt creator写的
  • ¥70 刚刚看到一个人的网站居然是通过cname访问的
  • ¥15 Attributeerror:super object has no attribute '__sklearn_tags__'_'
  • ¥15 逆置单链表输出不完整
  • ¥15 宇视vms-B200-A16@R启动不了,如下图所示,在软件工具搜不到,如何解决?(操作系统-linux)
  • ¥500 寻找一名电子工程师完成pcb主板设计(拒绝AI生成式答案)
  • ¥15 关于#mysql#的问题:UNION ALL(相关搜索:sql语句)
  • ¥15 matlab二位可视化能否针对不同数值范围分开分级?
  • ¥15 已经创建了模拟器但是不能用来运行app 怎么办😭自己搞两天了
  • ¥15 关于#极限编程#的问题,请各位专家解答!