我有MYSQL查询:
$sql = "SELECT * FROM cities WHERE ";
if ($city) { $where .= ($where ? " AND " : "")." ( city = '$city' ) "; }
if ($street) { $where .= ($where ? " AND " : "")."( street = '$street'"); }
if ($where) {
$sql .= $where;
$query = mysql_query($sql) or die(mysql_error($dbconnect_finder));
}
我想建立这个查询,如果找不到任何内容,它将使用OR运算符而不是AND。我知道我可以再次查询,如果没有重新开始的话。为了降低成本,我想在一个查询中完成。
编辑: 当用户搜索$ city和$ street时,将使用$ city =“Londan”(伦敦证明),$ street =“someStreet”。 AND运算符不起作用。然后OR运算符应该工作。是否可以在一个MYSQL查询中执行此操作?
答案 0 :(得分:0)
您可以尝试
$sql = "SELECT * FROM cities WHERE city = '$city' OR street = '$street'";
甚至你可以试试
$sql = "SELECT * FROM cities WHERE city = '$city'";
$result = mysql_query($sql);
if(count($result) == 0) {
$sql .= " OR street = '$street'";
$result = mysql_query($sql);
}
由于mysql_*
函数已弃用,因此最好使用mysqli_*
函数或PDO
语句。
答案 1 :(得分:0)
尝试执行此代码,我已经使用了一个名为city Present的变量,所以如果这是真的你和它,否则你或它/
$sql = "SELECT * FROM cities WHERE ";
$cityPresent = false;
if ($city) { $where .= ($where ? " AND " : "")." ( city = '$city' ) "; $cityPresent = true; }
if ($street && $cityPresent) { $where .= ($where ? " AND " : "")."( street = '$street'"); }
else { $where .= ($where ? " OR " : "")."( street = '$street'"); }
if ($where) {
$sql .= $where;
$query = mysql_query($sql) or die(mysql_error($dbconnect_finder));
}
答案 2 :(得分:0)
我希望这很有用:
$sql = "SELECT * FROM cities WHERE ";
if (isset($where)) {
if (isset($city)) {
$where .= " AND '$city'";
}
if (isset($street)) {
$where .= " AND '$street'";
}
$sql .= $where;
}
$query = mysql_query($sql) or die(mysql_error($dbconnect_finder));