doubushi0031 2013-08-22 11:28
浏览 46
已采纳

如何使用PHP和Codeigniter处理foreach中的mysql中的SELECT(MAX())

I'm using SELECT(MAX()) inside a foreach loop and this is my code:

foreach($_POST['image_Basename'] as $key=>$image_Basename){


    $image_Title = $this->input->post('image_Title');

    $image_Category_Id = $this->input->post('image_Category_Id');


    $this->db->query("INSERT INTO mg_gallery (image_Group_Id, image_title, image_Basename, image_Category_Id)
                      SELECT 1 + coalesce((SELECT max(image_Group_Id) FROM mg_gallery), 0), '$image_Title', '$image_Basename', '$image_Category_Id'
    ");
}

The problem is that for each image_Basename, query produces a new number.

For example, if I got 3 image_Basenames, it will insert 1, 2 and 3 for those three image_Basenames. But I want it to insert the same number to all of image_Basenames.

For example, if the max number in the image_Group_Id is 1, then add number 2 for each image_Basename. How can I do that?! I've put

SELECT 1 + coalesce((SELECT max(image_Group_Id) FROM mg_gallery

outside of the foreach loop, but it didn't work!!!

The answer is added below by myself

  • 写回答

4条回答 默认 最新

  • dsj8086 2013-08-22 20:24
    关注

    IT WORKS:

    Specially thanks to Niloy Saha, finally, I got the answer, and this is the code I've used:

    $getMaxValue  = $this->db->query('SELECT 1 + coalesce((SELECT MAX(image_Group_Id)), 0) AS image_Group_Id FROM mg_gallery');
    if($getMaxValue->num_rows() > 0){
        $group_Id    = $getMaxValue->row_array();
        $image_Group_Id  = $group_Id['image_Group_Id'];
    }else{
        $image_Group_Id  = 0;
    }
    
    foreach($_POST['image_Basename'] as $key=>$image_Basename){
        $image_Title = $this->input->post('image_Title');
        $image_Category_Id = $this->input->post('image_Category_Id');
        $this->db->query("INSERT INTO mg_gallery (image_title, image_Basename, image_Category_Id, image_Group_Id)
                          VALUES ('$image_Title', '$image_Basename', '$image_Category_Id', $image_Group_Id)
        ");
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备