dongyuan3094 2017-06-02 06:17
浏览 23
已采纳

日期未正确格式化为字符串

In this code I am converting date format dd-mm-yy to yy-mm-dd. When I echo $from date it gives the correct date (2017-6-1). Similarly with echo $to. But when I echo the query it can't get value of $from, but $to it gets the date correctly. What is the problem with $from?

Here is my code...

<script language='javascript'>
    jQuery(function($)
           { 
               $("#from").datepicker({ dateFormat: 'dd-mm-yy' });
               $("#to").datepicker({ dateFormat: 'dd-mm-yy' });
           });
</script>

<input name="from" id="from" type="text" />
<input name="to" id="to" type="text" />

<?php
    $froms = $_POST['from'];
    list($day, $month, $year) = explode("-", $froms);
    $from = "$year-$month-$day";

    $too = $_POST['to'];
    list($day, $month, $year) = explode("-", $too);
    $to = "$year-$month-$day";

    if($from = "$year-$month-$day" && $to = "$year-$month-$day")
    {
        echo "select * from students where (enquiry_date between '$from' and '$to')";
    }
?>

Result:

select * from students where (enquiry_date between '1' and '2017-06-09') order by student_id
  • 写回答

2条回答 默认 最新

  • dourao1877 2017-06-02 06:22
    关注

    First of all, you need to use '==' instead of '=' when you are comparing.

    Otherwise, I think you are trying to check if the date format is entered correctly.

    If so, replace line:

    if($from = "$year-$month-$day" && $to = "$year-$month-$day")
    

    with this line:

    if(validateDate($from) && validateDate($to))
    

    and make sure you define the function validateDate:

    function validateDate($date)
    {
        $d = DateTime::createFromFormat('Y-m-d', $date);
        return $d && $d->format('Y-m-d') == $date;
    }
    

    function was copied from this answer or php.net

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程