我的网站有一个动态查询(用于搜索功能)。它根据用户输入动态构建查询。
$query = "SELECT * FROM talents WHERE ";
if(!empty($_POST['firstName'])){
$query = $query . "firstName = '" . $_POST['firstName'] . "' AND ";
}
if(!empty($_POST['lastName'])){
$query = $query . "lastName = '" . $_POST['lastName'] . "' AND ";
}
if(!empty($_POST['gender'])){
$query = $query . "gender = '" . $_POST['gender'] . "' AND ";
}
if(!empty($_POST['eyeColor'])){
$query = $query . "eyeColor = '" . $_POST['eyeColor'] . "' AND ";
}
if($_POST['heightLow'] != "Low" && $_POST['heightHigh'] != "High"){
$query = $query . "height BETWEEN '" . $_POST['heightLow'] . "' AND '" . $_POST['heightHigh'] . "' AND ";
}else if($_POST['heightLow'] != "Low" && $_POST['heightHigh'] == "High"){
$query = $query . "height = '" . $_POST['heightLow'] . "' AND ";
}
if(!empty($_POST['hairColor'])){
$query = $query . "hairColor = '" . $_POST['hairColor'] . "' AND ";
}
if($_POST['weightLow'] != "Low" && $_POST['weightHigh'] != "High"){
$query = $query . "weight BETWEEN '" . $_POST['weightLow'] . "' AND '" . $_POST['weightHigh'] . "' AND ";
}else if($_POST['weightLow'] != "Low" && $_POST['weightHigh'] == "High"){
$query = $query . "weight = '" . $_POST['weightLow'] . "' AND ";
}
if(!empty($_POST['dressSize'])){
$query = $query . "dressSize = '" . $_POST['dressSize'] . "' AND ";
}
if($_POST['chestLow'] != "Low" && $_POST['chestHigh'] != "High"){
$query = $query . "chest BETWEEN '" . $_POST['chestLow'] . "' AND '" . $_POST['chestHigh'] . "' AND ";
}else if($_POST['chestLow'] != "Low" && $_POST['chestHigh'] == "High"){
$query = $query . "chest = '" . $_POST['chestLow'] . "' AND ";
}
if(!empty($_POST['shoeSize'])){
$query = $query . "shoeSize = '" . $_POST['shoeSize'] . "' AND ";
}
if($_POST['waistLow'] != "Low" && $_POST['waistHigh'] != "High"){
$query = $query . "waist BETWEEN '" . $_POST['waistLow'] . "' AND '" . $_POST['waistHigh'] . "' AND ";
}else if($_POST['waistLow'] != "Low" && $_POST['waistHigh'] == "High"){
$query = $query . "waist = '" . $_POST['waistLow'] . "' AND ";
}
if($_POST['hipsLow'] != "Low" && $_POST['hipsHigh'] != "High"){
$query = $query . "hips BETWEEN '" . $_POST['hipsLow'] . "' AND '" . $_POST['hipsHigh'] . "' ";
}else if($_POST['hipsLow'] != "Low" && $_POST['hipsigh'] == "High"){
$query = $query . "hips = '" . $_POST['hipsLow'] . "' ";
}
首先,忽略冗长的性质 - 这是一个开始工作的阿尔法。漂亮的代码之后。其次,High
andLow
变量引用范围搜索(例如,5'3 和 5'9 之间的高度)。
这是我的问题;AND
!_ 按照我的方式,如果输入有什么东西,它会起作用hips
,除了它会出错。但是,无法预测用户将在哪里停下来。
这是一个非常常见的功能,我很惊讶这在互联网上并不容易找到。有什么快速的想法吗?