php mysql基于IF语句向数组添加值

时间:2012-12-06 16:53:28

标签: php mysql joomla

使用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中是否存在arugments,为mySQL查询添加参数。我无法解决的问题是构建阵列并将其爆炸。

每当我在URL中放入一个参数时,所有表项都会填充。当我尝试传递一个参数时,它会出现空值。您可以在行动here中看到这一点。如果您向网址添加其他参数zip,则所有内容都会显示NULL

3 个答案:

答案 0 :(得分:0)

我认为问题是" WHERE 1=1"。尝试将此更改为此" WHERE 1=1 "。 因为最终查询将被附加到此,您将无法获得所需的结果。对于确认echo $query,请查看它是否是正确的查询。还有一件事是'" . $db->quote($city) . "'"。删除''因为你已经通过函数添加了它。

//更新:

最好使用where方法

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

答案 1 :(得分:0)

不确定这与前一个问题有何不同。

$查询 - >选择('*“); $查询 - >从($ DB-> nameQuote( '#__毫升'));

 $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

您无需构建任何数组;这就是拥有databasequery api的重点。

答案 2 :(得分: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有条件,但这不应该花费太多。至少现在有框架。感谢所有帮助过的人。

相关问题