0

I am trying to perform a query against a database with a combination of OR conditions. By filling out the form with corresponding fields in the database, after receiving the data, I put the query in such a way:

if ($state != '') {
    $xstate = " `State` LIKE '%" . $state . "%' ";
    $Isall = '0';
} else {
    $xstate=" `State` LIKE '-' ";
}

if ($dateStart != '' && $dateEnd != '') {
    $xdateStart = " `datefill`  BETWEEN '" . $dateEnd . "' AND '" . $dateStart . "'";
    echo $xdateStart;
    $Isall = '0';
}

as you can see, I check if the field is empty or not then I start to build the query, after asking all the relevant questions the query will look like:

$query="SELECT " .$field  . "  FROM  issueslog WHERE  ".$xdateStart." OR " .$xCode   ."   ;

and so on, my problem now is when I fill some field, for example xCode now is with data let say "900" and dateStart as you can see above is
$xdateStart=" datefill BETWEEN '".$dateEnd."' AND '".$dateStart."'";

so what I`m understood is that it will fetch data that corresponde to the code "900" between the specific dates, but what I get is result that coressponde only the the xCode 900, its seems that the date was abandoned.

I'd like to get suggestions, Thanks in advance.

EDIT
My generated query is:

SELECT *  FROM  issueslog WHERE   `datefill`  BETWEEN '2013-05-24' AND '2013-05-24' OR  `xCode` LIKE '-'  OR  `Address` LIKE '-'  OR  `tname` = '-'  OR  `fname` LIKE '-'  OR  `Phone1` LIKE '-'  OR  `State` LIKE '-'  OR  `City` LIKE '%TelAviv%' 
4

1 回答 1

0

你有代码行:

$query="SELECT " .$field  . "  FROM  issueslog WHERE  ".$xdateStart." OR " .$xCode   ." 

然后你说“所以我的理解是它会在特定日期之间获取与代码“900”相对应的数据”。

很简单。你的理解是错误的。该代码将获取与日期条件匹配的所有行,而不考虑 xCode以及与 xCode 条件匹配的所有行,而不考虑日期。如果您同时想要两者,那么您需要and

$query="SELECT " .$field  . "  FROM  issueslog WHERE  ".$xdateStart." AND " .$xCode   ." 

您的最终查询是

SELECT *
FROM  issueslog
WHERE   `datefill`  BETWEEN '2013-05-24' AND '2013-05-24' OR  `xCode` LIKE '-'  OR  `Address` LIKE '-'  OR  `tname` = '-'  OR  `fname` LIKE '-'  OR  `Phone1` LIKE '-'  OR  `State` LIKE '-'  OR  `City` LIKE '%TelAviv%' 

我想你想要的是:

SELECT *
FROM  issueslog
WHERE  ( `datefill`  BETWEEN '2013-05-24' AND '2013-05-24') AND
       (`xCode` LIKE '-'  OR  `Address` LIKE '-'  OR  `tname` = '-'  OR  `fname` LIKE '-'  OR  `Phone1` LIKE '-'  OR  `State` LIKE '-'  OR  `City` LIKE '%TelAviv%')

我的猜测是,如果任何合理的用户将日期范围放在表中的行上,那么该用户将需要该日期范围内的行。也许其他条件可以通过 连接OR。也许他们应该通过AND. 也许用户实际上应该可以选择指定如何连接这些条件。

于 2013-05-24T22:03:47.540 回答