doujiu3095 2014-05-10 23:49
浏览 62
已采纳

每个循环在PHP中重复两次日期

I've got a for each loop which is echoing results from a mysql query. Then I have a separate query inside the loop to find other records with a date value. I need to compare the dates to print relevant data however inside the loop the date is echoing twice like this:

echo $oneweeksbefore = date("d/m/Y", strtotime('-1 weeks'));

results in:

04/05/2014 04/05/2014

I'm having trouble comparing dates as below because of inaccurate dates.

foreach($data as $row) {
    $student_id = $row['student_id'];
    $sql = "SELECT end_date FROM table WHERE id = :id ORDER BY end_date DESC LIMIT 1";
    $q = $conn->prepare($sql);
    $q->execute(array(':id' => $student_id));
    $table = $q->fetch();
    $end_date = date("d/m/Y", strtotime($table[0]));
    $todaydate = date("d/m/Y");
    if (($end_date > $oneweeksbefore) && ($end_date < $todaydate))
    {
        $show_end_date = '<span class="label label-warning">'.$end_date.'</span>';
    }
    else
    {
        $show_end_date = '<span class="label label-info">'.$end_date.'</span>';
    }
}

The $oneweekbefore variable is outside of the foreach loop. I need to do the query inside of the loop because it needs to take the student_id from the first query for each row. And I can't incorporate it in one query because of more than one rows that needs to be limit to 1 as you can see above.

  • 写回答

1条回答 默认 最新

  • doulan3436 2014-05-11 00:43
    关注

    The repeated queries could be avoided by a rewritten query, that will get the latest end_date for every student_id:

    SELECT 
        id, 
        MAX(end_date) as max_end_date 
    FROM 
        thetable 
    GROUP BY 
        id 
    WHERE 
        id IN (<outer query goes here>)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题