【问题标题】:How to send HTML selected date to PostgreSQL in a Query如何在查询中将 HTML 选定日期发送到 PostgreSQL
【发布时间】:2020-04-04 01:36:08
【问题描述】:

我需要一点帮助,我一直在尝试将查询中的 2 的选定日期发送到 PostgreSQL,这样我就可以设置日期范围(介于之间),事实是我没有知道我是否做得对,用户设置日期并检查 isset($_POST['date1]),然后我这样做

if (isset($_POST['date1'])) {
    $var_fecha2 = $_POST['date'];
        if ($var_fecha2 ==0) { //this since can be empty and for some reason if it is my var gets 0, but as you can see its covered
            $fecha2_bool = true;
        }else {
            $fecha2_bool = false;
            $opt = 1;
        }
}

之后我有条件,但主要的是:

and sp.fec_grab between to_date('$var_fecha1','dd/mm/yyyy') and to_date('$var_fecha2','dd/mm/yyyy')

HTML 日期输入将日期作为 d-m-Y 发送,但作为字符串发送,我猜查询中的 to_date 将变量设置为日期,我还检查了 PostgreSQL 中的列并将其作为“d-m-Y” 谢谢!

【问题讨论】:

    标签: php html postgresql date


    【解决方案1】:

    考虑以下代码。它可能有错误,因为我没有测试过,但总体思路是这样的:

    // cheackout "ternary operator", it's a shorter syntax for if/else
    $from = isset($_POST['from']) ? date($_POST['from']) : false;
    $to = isset($_POST['to']) ? date($_POST['to']) : false;
    
    if (!$from) {
      // using die() as example, respond with better error to your request
      die("cannot query without a from date");
    }
    
    // validate from date
    // - replace '/' with your expected input date separator in explode()
    // - check the order of the elements in checkdate() to match your expected date inputs
    $from = explode('/', $from);
    if (count($from) != 3 || !checkdate($from[0], $from[1], $from[2]) {
      die("invalid from date");
    }
    
    // validate to date (only if present)
    if ($to !== false) {
      $to = explode('/', $to);
      if (count($to) != 3 || !checkdate($to[0], $to[1], $to[2]) {
        die("invalid to date");
      }
    }
    
    // Ready to query
    if (!$to) {
      // query: ...and sp.fec_grab > '$from'
    } else {
      // query: ...and sp.fec_grab between '$from' and '$to'
    }
    

    有用的链接

    【讨论】:

      猜你喜欢
      • 2021-11-24
      • 2012-03-05
      • 1970-01-01
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多