将查询字符串与多个连接连接在一起

时间:2014-02-03 17:15:16

标签: php mysql sql

我很新加入并根据字段动态生成它们。

所有关键变量($ et_key,$ ct_key,$ key)都是根据映射到数据库列名的下拉值生成的。例如:

$state = $_POST['geography'];

$states = array('Alabama','Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District Of Columbia', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts ', 'Michigan', 'Minnesota', 'Mississippi ', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming');

$key = array_search($state, $states);

    if ($key !== false) {
        $state_key = $key+1;
    } 

这是我的完整查询代码。我主要感到困惑的是如何处理所有“和”线----第一个不能有“和”,但据我所知,后续的必须。我不确定如何解决这个问题。我没有重构这个或任何东西,抱歉丑陋的重复性。

$query=("SELECT * FROM exchange");

if($et_key) {
    $query .= " INNER JOIN`exchange_type` on `exchange_type`.exchangeID = exchange.exchangeID ";
}

if($ct_key) {
    $query .= " INNER JOIN `company_type` ON `company_type`.exchangeID = exchange.exchangeID ";
}

if($key) {
    $query .= " INNER JOIN `exchange_states` on `exchange_states`.exchangeID = exchange.exchangeID ";
}

if ($et_key || $ct_key || $key) {
    $query .= " where ";
}

if($et_key) {
    $query .= " and `exchange_type`.$et_key=1 ";
}

if($ct_key) {
    $query .= " and `company_type`.$ct_key = 1 ";
}

if($key) {
    $query .= " and exchange_states`.stateID = $state_key ";
}


if (!empty($keywork)) {
    $query .= "and (exchange.`exchange-name` LIKE '%$search%' OR exchange.`description` LIKE '%$search%')";
}


echo $query;

1 个答案:

答案 0 :(得分:0)

更改此内容:

if ($et_key || $ct_key || $key) {
   $query .= " where ";
}

到此:

if ($et_key || $ct_key || $key) {
   $query .= " where 1=1 ";
}

然后,“ands”都有意义