gpt4 book ai didi

php - 成员(member)搜索功能

转载 作者:行者123 更新时间:2023-11-30 23:27:31 25 4
gpt4 key购买 nike

我试图为页面上的搜索功能提出 MySQL 逻辑。它是一个简单的表单,用户可以在其中选择填写搜索条件。条件作为参数发送到生成 mysql 逻辑的函数。这是 PHP Controller 文件中的内容:

   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() 条件,但我仍然无法提出满足我需要的正确代码。如果有人能给我指出正确的方向,我就可以自己完成剩下的工作。也欢迎任何其他解决此类问题的方法。

最佳答案

如果我理解你的问题,那么简单的方法就是使用 if else 来构建 sql 查询,例如

$sql = "SELECT username FROM profiles WHERE 1 "
if (!is_null($username)) {
$sql .= " AND username = :username ";
}
// All other checks

关于php - 成员(member)搜索功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12499116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com