我正在尝试为多个可选字段上的搜索编写SQL查询。首先我使用 column_name =用户输入的值制作它,工作正常;
但是当我将其更改为 column_name LIKE%用户输入的值%时,它会显示为%'值'%和单引号(&# 39;)正在制造麻烦。请告诉我如何克服这一点。
mysql_select_db($database_BMProperty, $BMProperty);
if(isset($_POST['City'])) {$A=sprintf(GetSQLValueString($_POST['City'], "text"));} else {$A="any";}
if(isset($_POST['Locality'])) {$B=**"%".sprintf(GetSQLValueString($_POST['Locality'], "text"))."%"**;}else {$B="any";}
if(isset($_POST['PIN'])) {$C=sprintf(GetSQLValueString($_POST['PIN'], "text"));} else {$C="any";}
if(isset($_POST['BedRooms'])) {$D=sprintf(GetSQLValueString($_POST['BedRooms'], "int"));} else {$D="any";}
if(isset($_POST['Area'])) {$E=sprintf(GetSQLValueString($_POST['Area'], "int"));} else {$E="any";}
if(isset($_POST['BuyRent'])) {$F=sprintf(GetSQLValueString($_POST['BuyRent'], "int"));} else {$F="any";}
$string = "";
if(isset($_POST['City'])&& $_POST['City'] !='') {$string= "CITY = $A";
}
if(isset($_POST['Locality']) && $_POST['Locality'] !='' ) {if($string != "") {$string .= " **AND LOCALITY LIKE $B**";} else {$string .= "LOCALITY = $B";}
}
if(isset($_POST['PIN']) && $_POST['PIN'] != '') { if($string != "") {$string .= " AND PIN = $C";} else {$string .= "PIN = $C";}
}
if(isset($_POST['BedRooms']) && $_POST['BedRooms'] != '' ) { if($string != "") {$string .= " AND BEDROOMS = $D";} else {$string .= "BEDROOMS = $D";}
}
if(isset($_POST['Area']) && $_POST['Area'] !='') { if($string != "") {$string .= " AND AREA = $E";} else {$string .= "AREA = $E";}
}
if($F != 'any'){ // or whatever you need
$where[] = "BUYRENT = $F";
if($string != "") {$string .= " AND BUYRENT = $F";} else {$string .= "BUYRENT = $F";}
}
$query = "SELECT * FROM ads";
if($string){
$query .= ' WHERE ' . $string;
}
查询是这样的:
SELECT * FROM ads WHERE CITY = 'mumbai' AND LOCALITY LIKE %'thane'% AND BUYRENT = 1
City和BuyRent是必填字段。