【问题标题】:can't access value of input when i have it inside foreach loop (using post method)当我在 foreach 循环中(使用 post 方法)时无法访问输入的值
【发布时间】:2019-11-01 20:08:50
【问题描述】:

我有一个包含一个输入(类型按钮)和一个图像的表单。 当我单击它应该删除图像的按钮时(提交表单并获取输入的值,即图像的 id,使用 post 方法)。 但是当我在 foreach 循环中有输入时,我无法访问它的值。 因为在 foreach 中创建的每个输入都具有相同的名称。 https://i.imgur.com/ed9Vv9m.png

我尝试了 var_dump,但只有空值。

这是相机视图中的表单:

foreach($data['galleries'] as $gallery) :
    ?>
    <div align=center>
    <form action="<?php echo URLROOT; ?>/gelleries/camera" 
   method="post">
    <input type="button" class="button" name="delete" id="abc" 
   value="<?php echo $gallery->galleryId; ?>" onclick="return 
   Deleteqry(<?php echo $gallery->galleryId; ?>);">
    </div>
    </form>
    <?php endforeach; ?>

这是控制器:

<?php
    class Galleries extends Controller {
     $this->galleryModel = $this->model('Gallery');
   }
    $galleries = $this->galleryModel->hiFive();
    $datashow = [
        'galleries' => $galleries
    ];
    .....
    public function camera(){
     if (isset($_POST['delete']) && !empty($_POST["delete"])){
        $imgid = $_POST["delete"];
      $this->galleryModel->deleteimg($imgid);
      echo "deleted!";
    exit;
 }
 else
    echo "error";
    $this->view('/galleries/camera', $datashow);
 }

这是我执行查询的模型:

<?php
   class Gallery {
   private $db;

   public function __construct(){
    $this->db = new Database;
   }
   .....
      public function deleteimg($id){
       $this->db->query("DELETE FROM galleries WHERE id = :id");
       $this->db->bind(':id', $id);
       if($this->db->execute()){
       return true;
     } else {
      return false;
   }
   }
   }

按钮的onclick事件中的Deleteqry只是一个函数,当我点击按钮时,我会检查是否获得了图像的ID:

function Deleteqry(id)
{ 
 if(confirm("Are you sure you want to delete this row?")==true)

 window.location="http://localhost:8001/camagru/galleries/camera? 
 &del="+id;
  return false;
 }

【问题讨论】:

  • 在循环中创建多个表单或多或少都可以,但您必须确保任何具有 ID 属性的元素都具有唯一 ID,而不是 id="abc"
  • @RamRaider 我现在用 galleryId; ?> .. 所以每个元素都有唯一的 id .. 但我仍然无法删除图像
  • Deleteqry 是做什么的?您尚未将其添加到问题中
  • 这只是一个 javascript 函数,当我点击按钮时,我会检查是否获得了每张图片的 id .. 我现在将其添加到上面的帖子中

标签: php forms post foreach


【解决方案1】:

在表单块中添加隐藏的输入字段,其值为画廊 ID,如下所示:

 <form ...>
    <input type="button" class="button" name="delete" value="DELETE NOW">
    <input type="hidden" name="GallID" value="<?php echo $gallery->galleryId;?>" >
 </form> 

然后在您的控制器中从隐藏字段中读取该值:

if (isset($_POST['delete']) && isset($_POST['GallID']) && !empty($_POST["delete"])){
    $imgid = $_POST["GallID"];
    $this->galleryModel->deleteimg($imgid);
    echo "deleted!";
}

这在没有 javascript 的情况下完全可以工作。

【讨论】:

    猜你喜欢
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 2019-06-17
    • 1970-01-01
    • 2015-08-22
    相关资源
    最近更新 更多