【发布时间】:2012-09-19 16:38:55
【问题描述】:
我正在尝试为我在我的页面上获得的搜索功能提出 MySQL 逻辑。它是一个简单的表格,用户可以选择填写搜索条件。条件作为参数发送到生成 mysql 逻辑的函数。这是 PHP 控制器文件中的内容:
case 'search':
if((empty($_POST['username'])) && (empty($_POST['firstname'])) && (empty($_POST['lastname']))
&& (empty($_POSt['agemin'])) && (empty($_POST['agemax'])) && (empty($_POST['country']))){
$members = get_all_username();
} else {
if(isset($_POST['username'])){
$otheruser = $_POST['username'];
} else { $otheruser = null; }
if(isset($_POST['agemin'])){
$ageMin = $_POST['agemin'];
} else { $ageMin = null; }
if(isset($_POST['agemax'])){
$ageMax = $_POST['agemax'];
} else { $ageMax = null; }
if(isset($_POST['country'])){
$country = $_POST['country'];
} else { $country = null; }
//if(isset($_POST['isonline']))
$members = search_members($otheruser, $ageMin, $ageMax, $country);
}
include('displaySearch.php');
break;
因此,如果未设置任何内容,则会生成并显示所有成员的完整列表。这是在设置任何输入时调用的函数:
function search_members($username, $ageMin, $ageMax, $country){
global $db;
$query = "SELECT username FROM profiles WHERE username = :username
AND age > :ageMin AND age < :ageMax AND country = :country";
$statement = $db->prepare($query);
$statement->bindValue(':username', $username); $statement->bindValue(':ageMin', $ageMin);
$statement->bindValue(':ageMax', $ageMax); $statement->bindValue(':country', $country);
$statement->execute();
if($statement->rowCount() >= 1){
return $statement->fetchAll();
} else {
return false;
}
}
mysql的逻辑显然是错误的。 我需要一组条件(如果可能,在 MySQL 逻辑中)检查 PHP 变量的值,如果没有,则在查询数据库时不应该考虑它。 所以如果只有用户名是在表单中设置其他变量不应包含在 SQL 逻辑中。
我已经查看了 MySQL IF() 条件,但我仍然无法提出符合我需要的正确代码。如果有人能指出我正确的方向,我就可以自己做剩下的事情。也欢迎任何其他解决此类问题的方法。
【问题讨论】:
-
您检查的条件是什么?
-
检查 PHP 变量是否有用户输入值或设置为 null(在控制器 php 文件中完成)。我认为DTukans给出的解决方案很好。根据 PHP 变量是否为空来连接 sql 逻辑。我会尝试并返回结果。