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条)

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测