php - Mysql的搜索功能

标签 php mysql

我正在尝试设置一个搜索功能,我可以在其中输入我想要的内容,也可以从下拉菜单中选择它,但是当字段为空时,我希望它显示所有内容。

现在,当我搜索某些内容时,它会起作用,但是当字段为空时,它根本不显示任何内容。我正在使用prepare和bind_params来设置mysql查询,这就是为什么设置变得困难,因为如果变量为空,我不知道如何轻松删除查询的该部分并更改正在绑定(bind)的变量的数量到查询。这是查询

$stmt = $conn->prepare("SELECT * FROM re_tblcombinationlist WHERE active != ? AND ModifierKey = ? AND (LootItem1Key = ? OR LootItem2Key = ? ) ORDER BY ReportedOn DESC LIMIT ? , ?");
$stmt->bind_param("isssii", $i = 0, $modifier, $lootsearch, $lootsearch, $limits, $max);
$recent1 = infoo($stmt);

我尝试通过添加此 if then 语句来解决它,但它没有改变任何内容

if(!isset($_POST["modifier"])){
$modifier = '';
}else{
$modifier = clean($_POST["modifier"]);
}

if(!isset($_POST["lootsearch"])){
$lootsearch = '';
}else{
$lootsearch = clean($_POST["lootsearch"]);
}

基本上,如果修饰符或战利品搜索为空,我不希望该部分出现在 mysql 查询中,这很容易做到,但是它使得处理要绑定(bind)的变量数量变得非常困难,所以我试图找到一个如果变量为空,则使其搜索所有内容的方法。

谢谢

最佳答案

我认为我基于此找到了解决您问题的方法:http://php.net/manual/en/mysqli-stmt.bind-param.php#109256

首先创建这个类:

class BindParam { 
    private $values = array();
    private $types = ''; 

    public function add( $type, $value ){ 
        $this->values[] = $value; 
        $this->types .= $type; 
    } 

    public function get() { 
        return array_merge(array($this->types), $this->values); 
    } 
}

此后,请确保在代码中导入该类,然后在搜索文件中插入以下行:

//User inputs, just for testing
$active = 0;
$modifier = 5;
$lootsearch = 'item';
$limits = 3;
$max = 5;

//Conditional binding
$bindParam = new BindParam(); 
$binds = array(); 
$binds[] = 'active = ?';
$bindParam->add('i', $active);

$query = "SELECT * FROM re_tblcombinationlist WHERE ";
if (!empty($modifier)) {
    $binds[] = 'ModifierKey = ?';
    $bindParam->add('s', $modifier);
} 
if (!empty($lootsearch)) {
    $binds[] = ' (LootItem1Key LIKE ? OR LootItem2Key LIKE ?) ';
    $bindParam->add('s', $lootsearch);
    $bindParam->add('s', $lootsearch);
}

$query .= implode(" AND ", $binds);
$query .= " ORDER BY ReportedOn DESC LIMIT ? , ?";

$bindParam->add('i', $limits);
$bindParam->add('i', $max);

//Uncomment this for debugging

//echo $query . '<br/>';

//Using the above user inputs query should be:
//SELECT * FROM re_tblcombinationlist WHERE active = ? AND ModifierKey = ? AND (LootItem1Key LIKE ? OR LootItem2Key LIKE ?) ORDER BY ReportedOn DESC LIMIT ? , ?

//var_dump($bindParam->get());

//Maybe you have to experiment a bit with those lines
$stmt = $conn->prepare($query);
$stmt->bind_param($bindParam->get());
$recent1 = infoo($stmt);

关于php - Mysql的搜索功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32927759/

相关文章:

javascript - 显示另一个页面中 2 个下拉菜单中的条目

php - 将 symfony 升级到 3.0 - 错误的分发包版本

php - 使用ajax登录安全吗?

php - 我应该在 php 中缓存整个查询还是应该只缓存行的主键?

php - 使用php将excel表上传到mysql

php - 查询 SQL 在 ajax jquery 中不起作用

javascript - Mysql通过Ajax插入查询

php - 是否有任何用于 PHP 的开源文本分析库?

mysql - 运行缓慢的 SQL 查询

mysql从另一个表更新表