当表单具有多个相似字段时,是否可以仅发送相关数据?

时间:2019-01-24 21:49:40

标签: php

我正在尝试在我的项目上重新创建“注释部分”。我有一个循环来显示许多“帖子”,并且每个帖子都有自己的注释部分,全部位于同一Form中。因此,我最终会有多个名称相似的字段(即button1,button2,button3等,等等,每个帖子一个)。是否有可能有一个isset($ post ['button'])适合所有情况,并且只带来与我单击的信息有关的信息?

我可以让每个帖子都是一个单独的表格,但是那样的话我会做很多事情。我希望有办法解决这个问题

这就是我拥有的:

input type='text' name='post_comment".$k."' class='form-control' value=''
input type='submit' class='btn' name='postComment".$k."' value='Comment'


...


if(isset($post['postComment'])){
   //do something
}

如果我将$ k硬编码到我的isset中(即isset($ post ['postComment34'])),一切都会按我的意愿工作。我的isset是否可以接受任何“ postCommentxx”?

2 个答案:

答案 0 :(得分:0)

您确实需要使用具有匹配索引的数组:

<input type='text' name='post_comment[$k]' . . . 
<input type='submit' name='postComment[$k]' . . .

然后,您可以使用提交的索引来获取文本:

if(isset($post['postComment'])){
    $key  = key($_POST['postComment']);
    $text = $_POST['post_comment'][$key];
}

我会将postComment更改为submit之类的名称,因为具有相同名称的变量只是稍有不同会令人困惑。

答案 1 :(得分:0)

欢迎来到Stackoverflow!

因此,如果我对您的问题的理解正确,那么您只想使用1个表格,而不要使用多个表格发送帖子评论。尝试使用<button type='submit'>代替<input type='submit>'。看我的例子:

<input type='text' name='post_comment".$k."' class='form-control' value=''>
<button type='submit' class='btn' name='postComment' value='".$k."'>Comment</button>

现在您可以继续使用您的php代码;

if (isset($_POST['postComment'])) {
    $postid = $_POST['postComment'];
    $comment = $_POST['post_comment'.$postid];
    // Do something
}

就是这样! (希望我能帮助您:P)