0

我在 joomla view php 上有这个代码:(这个代码生成月份下拉列表)

    <form action="<?php echo JRoute::_('index.php?option=com_mycom'); ?>" method="post" name="adminForm" id="adminForm" class="modelList">        
    <select name="filter.search" class="inputbox" onchange="this.form.submit()">
                        <?php
          for ($i = 0; $i <= 12; ++$i) {
            $time = strtotime(sprintf('-%d months', $i));
            $value = date('Y-m', $time);
            $label = date('F Y', $time);
            printf('<option value="%s">%s</option>', $value, $label);
          }
          ?>
          </select>
</form>

我有一个带有“日期”行的mysql表调用“日期”所以我正在寻找的是 - 当我选择月份时,这个月的所有数据都将加载到这个页面上

那么我怎样才能从 sql 查询中得到它呢?我在模型上尝试此代码,但这给了我一个错误:

    $search = $this->getState('filter.search');

    if(!empty($search))
    {
        if(stripos($search, 'id:') === 0)
        {
            $query->where('id = '.(int) substr($search, 3));
        }
        else
        {
            $search = $db->Quote('%'.$db->escape($search, true).'%');
            $query->where('(date LIKE '.$search.')');
        }
    }

我试试这个代码:

if(!empty($search))
    {
        if(stripos($search, 'id:') === 0)
        {
            $query->where('a.id = '.(int) substr($search, 3));
        }
        else
        {

            $searchParts = explode('-', $search);
            // day 1 of selected month
            $searchStartDate = date('Y-m-d', mktime(0, 0, 0, $searchParts[1], 1, $searchParts[0]));
            // day 0 of next month is last day of selected month
            $searchEndDate = date('Y-m-d', mktime(0, 0, 0, $searchParts[1] + 1, 0, $searchParts[0]));

            $query->where("(a.date BETWEEN '$searchStartDate' AND '$searchEndDate' LIKE '.$search.')");
        }
    }

但它返回一个错误:

Fatal error: Call to a member function where() on a non-object in 

在这条线上——$query->where("(a.date BETWEEN '$searchStartDate' AND '$searchEndDate' LIKE '.$search.')");

4

1 回答 1

0

使用 DATE 字段时,您应该这样做。您正在尝试将其作为字符串使用,这是可能的,但效率非常低。

与其要求数据库返回所有记录WHERE date LIKE '%2013-07%',不如询问所选月份开始和结束之间的所有记录。

SELECT *
FROM tbl
WHERE `date` BETWEEN '2013-07-01' AND '2013-07-31'

您可以将您的 PHP 代码更改为这样的 -

else
{
    $searchParts = explode('-', $search);
    // day 1 of selected month
    $searchStartDate = date('Y-m-d', mktime(0, 0, 0, $searchParts[1], 1, $searchParts[0]));
    // day 0 of next month is last day of selected month
    $searchEndDate = date('Y-m-d', mktime(0, 0, 0, $searchParts[1] + 1, 0, $searchParts[0]));

    $query->where("(date BETWEEN '$searchStartDate' AND '$searchEndDate')");
}
于 2013-07-25T09:02:49.797 回答