如何使用php在sql之间显示开始日期和结束日期之间的数据或开始时间和结束时间?

时间:2018-06-18 05:51:39

标签: php mysql cakephp

我开发了一个Web服务并将数据从SQL发送到API。但是,是基于开始日期和结束日期,还是开始时间和结束时间,但结果并不完美。

CakePHP查询代码:

$Home = $this->Home->find('all',array(
          'contain' => array('LiveVideo' => array(
            'conditions' => array(
                        array('OR' => array('DATE(LiveVideo.from_date) >=' => date('Y-m-d')),
                        array('DATE(LiveVideo.to_date) <=' => date('Y-m-d')))



                        //'LiveVideo.from_time >=' => date('h:i'),
                        //array('LiveVideo.to_time <=' => date('h:i'))

                )

            )),

          'fields' => array(),
          'order' => 'Home.created DESC',             
    ));

我想在开始日期和开始时间或结束日期和结束时间之间产生结果。

2 个答案:

答案 0 :(得分:0)

这是日常应用中最基本的问题之一。如果问题仅与数据库有关,答案是最好的。

根据您应用的标签,我认为它与基于PHP的动态网页相关。如果您使用的是Core PHP,那么您可以按照以下脚本部分进行复制和粘贴。所有解释都以评论的形式出现:

<?php
/**
 * Connect to mysql server from php script
 * Please replace the credentials as per your environment configuration
 * Parameters details :
 * "localhost" -- It is Hostname where mysql server is installed
 * "root" -- Default username for mysql
 * "password" -- Password for MySQL Database user, Can be left blank if there is no password
 * "test" -- It is the database which contains project data
 */ 
$mysqli = new mysqli("localhost", "root", "password", "test");
/**
 * Now setting the query parameters
 */
$startDate="2015-01-01";
$endDate="2015-12-31";
/**
 * Lets execute query on MySQL
 * here used columns are
 * OrderDate -- replace it with your date field
 * OrderNo -- replace with fields you want in your results
 * orders -- replace with name of table you want to use 
 */
$mysqli->real_query("
     SELECT OrderDate,OrderNo
     FROM orders
     WHERE OrderDate BETWEEN '{$startDate}' AND '{$endDate}'
     ORDER BY OrderDate ASC
");
/**
 * Get result buffer
 */
$res = $mysqli->use_result();

echo "Result from table...<br />";
/**
 * Printing result on web page with while loop
 */
while ($row = $res->fetch_assoc()) {
   echo " OrderDate = " . $row['OrderDate'] . " OrderNo = " . $row['OrderNo'] . "<br />";
}

在CakePHP中

<?php

$start = new Time('2018-01-01');
$end = new Time('2018-01-31');

$table = $this->Tables->find('all')
  ->contain(['AssocTables' => function ($q) use ($start, $end){
    return $q->where(['AssocTables.start >=' => $start, 'AssocTables.end <=' => $end])
  }]);

答案 1 :(得分:0)

你几乎是对的。只需从您的查询中删除“OR”子句(date&gt; = startDate AND date&lt; = endDate)

您还需要指定日期格式,以便将日期与php进行比较

      $Home = $this->Home->find('all',array(
              'contain' => array('LiveVideo'),
              'conditions' => array('DATE_FORMAT(LiveVideo.from_date, "%Y-%m-%d") >=' => date('Y-m-d'), 'DATE_FORMAT(LiveVideo.to_date, "%Y-%m-%d") <=' => date('Y-m-d')),
              'fields' => array(),
              'order' => 'Home.created DESC',             
  );