0

使用 Joomla,在尝试基于 URL 参数构建 mySQL 查询时遇到问题。我的代码如下所示:

    $db =& JFactory::getDBO();
    $hpprice = JRequest::getVar('hprice');
    $lprice = JRequest::getVar('lprice');
    $city = JRequest::getVar('city');
    $zip = JRequest::getVar('zip');
    $bdrms = JRequest::getVar('bdrms');
    $bths = JRequest::getVar('bths');

    $query = "SELECT * FROM " . $db->nameQuote('#__mls') . " WHERE 1=1";
    $clauses = array();
    if ($zip != null) {
        $clauses[] = $db->nameQuote('MSTZIP') . " = " . $db->quote($zip);
    }
    if ($city != null) {
        $clauses[] = $db->nameQuote('MSTCITY') . " = '" . $db->quote($city) . "'";
    }
    if ($bdrms != null){
        $clauses[] = $db->nameQuote('MSTBDRMS')." >= ".$db->quote($bdrms);
    }
    if ($bths != null){
        $clauses[] = $db->nameQuote('MSTBATHS') . " >= " . $db->quote($bths);
    }
    if ($lprice != null){
        $clauses[] = $db->nameQuote('MSTLISTPRC') . " BETWEEN " . $db->quote($lprice) . " AND " . $db->quote($hprice);
    } 

    $query .= implode(" AND ", $clauses);

    $db->setQuery($query);
    $table = $db->loadRowList();
    return $table;

因此,如您所见,根据 URL 中是否存在参数,向 mySQL 查询添加参数。我无法理解的是构建阵列并将其内爆。

每当我在 URL 中输入参数时,都会填充所有表格项。当我尝试传递一个参数时,它会出现空值。您可以在这里看到这一点。如果您zip在 URL 中添加另一个参数,那么一切都会出现NULL

4

3 回答 3

0

不确定这与您之前的问题有何不同。

$query->select('*"); $query->from($db->nameQuote('#__mls'));

 $query->where('1 = 1', AND);
if ($zip != null)
{
  $query->where (.$db->nameQuote('MSTZIP')." = ".$db->quote($zip)); 
}
if ($city != null) 
{ 
   $query->where($db->nameQuote('MSTCITY')." = '".$db->quote($city)); 
} 

Etc

您无需构建任何数组;这就是拥有数据库查询 api 的全部意义所在。

于 2012-12-06T23:43:13.140 回答
0

我认为问题是这个" WHERE 1=1"。试着把这个改成这个- " WHERE 1=1 "。因为最终查询将附加到此,您将不会得到期望的结果。为了确认,还echo $query请查看它是否是正确的查询。还有一件事是'" . $db->quote($city) . "'".remove '',因为您已经通过函数添加了它。

//更新:

最好使用where方法

如果这不起作用,请告诉我。

于 2012-12-06T20:08:20.073 回答
0

最终脚本最终看起来像这样:

    $db =& JFactory::getDBO();
    $hprice = JRequest::getVar('hprice');
    $lprice = JRequest::getVar('lprice');
    $city = JRequest::getVar('city');
    $zip = JRequest::getVar('zip');
    $bdrms = JRequest::getVar('bdrms');
    $bths = JRequest::getVar('bths');

    $query = "SELECT * FROM " . $db->nameQuote('#__mls') . " WHERE 1=1 AND ";
    $clauses = array();
    if ($zip != null) {
        $clauses[] = "MSTZIP = " . $zip;
    }
    if ($city != null) {
        $clauses[] = "MSTCITY = " . $db->quote($city);
    }
    if ($bdrms != null){
        $clauses[] = "MSTBDRMS >= " . $bdrms;
    }
    if ($bths != null){
        $clauses[] = "MSTBATHS >= " . $bths;
    }
    if ($lprice != null){
        $clauses[] = "MSTLISTPRC BETWEEN " . $lprice . " AND " . $hprice;
    } 

    $query .= implode(" AND ", $clauses) . ";";

    $db->setQuery($query);
    $table = $db->loadRowList();
    return $table;

我最终摆脱了nameQuotequote除非需要/适用。我正在使用的脚本模型来自一些教程。它适用于我以前所做的事情,但由于某种原因现在不行。最后一步是使初始AND条件成为条件,但这应该不会花太多时间。至少框架现在在那里。感谢所有帮助过的人。

于 2012-12-07T15:06:01.673 回答