[英]Building a Dynamic MySQL Query Based on Multiple Variables and Conditions
我希望这个标题很好地代表了这个问题。 我正在尝试基于现有的多个$ vars构建动态查询。 我试图使用简单的if / ifelse / else块来完成这项工作,但似乎无法让它正常工作。 第一个if语句相应地执行但第三个失败。 我是PHP的新手,所以我假设这是一个初学者的错误。 我也相信,很有可能是一种更有说服力的方法来实现预期的结果。
基本上,用户将一些输入输入到多个文本字段中。 3个中只有一个字段需要包含一个值,但也可以包含2个或全部3个字段。 如果字段中不存在该值,则应根据提供的值生成查询。 我正在验证并为每个输入创建一个变量,而不是检查这些变量是否包含值或存在。
//////////////////////////////////////////////////////
if(isset($_POST['inputName']) && $_POST['inputName'] != ""){
$inputName = preg_replace('#[^a-z 0-9?!]#i', '', $_POST['inputName']);
}
if(isset($_POST['inputState']) && $_POST['inputState'] != ""){
$inputState = preg_replace('#[^a-z 0-9?!]#i', '', $_POST['inputState']);
}
if(isset($_POST['inputCost']) && $_POST['inputCost'] != ""){
$inputCost = preg_replace('#[0-9]#i', '', $_POST['inputCost']);
}
///////////////////////////////////////////////////////
if (!empty($inputName) AND !empty($inputState) AND !empty($inputCost)){
$sqlCommand = "SELECT * FROM hciproject WHERE school_name LIKE '%$inputName%' AND school_state LIKE '%$inputState%' AND school_cost < '$inputCost'";
}
elseif (!empty($inputName) AND !empty($inputState)){
$sqlCommand = "SELECT * FROM hciproject WHERE school_name LIKE '%$inputName%' AND school_state LIKE '%$inputState%'";
}
elseif (!empty($inputName) AND !empty($inputCost)){
$sqlCommand = "SELECT * FROM hciproject WHERE school_name LIKE '%$inputName%' AND school_cost < '$inputCost'";
}
elseif (!empty($inputState) AND !empty($inputCost)){
$sqlCommand = "SELECT * FROM hciproject WHERE school_state LIKE '%$inputState%' AND school_cost < '$inputCost'";
}
else{
$searchOut .= "0 Results Found";
}
// Connect to DB
include_once("database_connection.php");
$query = mysql_query($sqlCommand) or die(mysql_error());
$count = mysql_num_rows($query);
///////////////////////////////////////////////////////
另外,我打算创建仅包含一个变量的elseif语句。
任何有关这方面的帮助将不胜感激。
尝试这个:
$inputName = preg_replace('#[^a-z 0-9?!]#i', '',& $_POST['inputName']);
$inputState = preg_replace('#[^a-z 0-9?!]#i', '',& $_POST['inputState']);
$inputCost = preg_replace('#[0-9]#i', '',& $_POST['inputCost']);
$selectCondition = 1;
if($inputName) $selectCondition.= " and school_name LIKE '%$inputName%' ";
if($inputState ) $selectCondition.= " and school_state LIKE '%$inputState%' ";
if($inputCost ) $selectCondition.= " and school_cost < $inputCos ";
重要:
& $_POST['inputName'] is equal to (isset($_POST['inputName']) && $_POST['inputName'] != "")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.