doukengzi3517 2019-07-18 10:41
浏览 171

日期列是varchar如何选择数据,直到今天01-01-2019

I have a problem with fetch data. Date is saved in VARCHAR, which means it will string. I want to select data from 01-01-2019 to today in my table. So I have problem in where class condition.

Please check code below where I am trying to fetch data but it's still not working. I am using STR_TO_DATE(holiday_date, '%d-%m-%Y') for change format string to date column.

<?php 
echo  $edate=date('d-m-Y');
$query="SELECT * FROM holidays where STR_TO_DATE(holiday_date, '%d-%m-%Y')='$edate' ORDER BY STR_TO_DATE(holiday_date, '%d-%m-%Y') asc ";
$stmt=$conn->prepare($query);
$stmt->execute();
$i=1;
    while ($result = $stmt->fetch()) {
    ?>
<tr class="holiday-completed">
    <td><?php echo $i;?></td>
    <td style="display: none;"><?php echo $result['id'];?></td>
    <td><?php echo $result['title'];?></td>
    <td><?php echo $result['holiday_date'];?></td>
    <td>
        <?php $s=$result['holiday_date'];
                $sdate = strtotime($s);
                echo date('l',$sdate);
        ?>
    </td>
  • 写回答

2条回答 默认 最新

  • dongxingji3882 2019-07-18 10:49
    关注

    A query like this, then:

    SELECT * 
    FROM holidays 
    WHERE STR_TO_DATE(holiday_date, '%d-%m-%Y') BETWEEN STR_TO_DATE('01-01-2019', '%d-%m-%Y') AND NOW()
    ORDER BY STR_TO_DATE(holiday_date, '%d-%m-%Y') asc
    

    But really, you should sort your data out;

    • make a new column of date type,
    • run a query like UPDATE table SET holiday_date_PROPER = STR_TO_DATE(holiday_date, '%d-%m-%Y') to prepopulate
    • create a trigger to convert the string to date once (upon insert or update) so that future insertions and updates are also handled,
    • query the date column not the varchar column (saves hundreds of conversions that are necessary every time you run your select query - over your app's life it will save millions of conversions),
    • switch your app to using the date column,
    • delete the varchar column
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程