PHP - 查询空值

标签 php mysql sql

我想创建一个像 this post 这样的表单,但我想这样做,以便如果其中一个输入为空,那么 php 仍将处理查询。我使用 INNERJOIN 还是 LEFTJOIN

编辑: 这是来自 that post 的 html 表单:

<form action="results.php" method="GET">
  <input type="text" name="input">
  <input type="text" name="topic">
  <input type="text" name="location">
</form>

以及它的 php 代码:

$db = new mysqli(*your database connection information here*);
$input = $_GET['input']; //this is for the text input - ignore
$topic = $_GET['topic']; // the first select box value which works well
$location = $_GET['location']; //the second select box value which isn't being inserted into the query
$combined = $input . $topic . $location;
$terms = explode(" ", $combined);
$stmt = $db->prepare("SELECT * FROM search WHERE input = ? AND topic = ? AND location = ?");
$stmt->bind_param("sss", $input, $topic, $location);
$stmt->execute();
$stmt->close();

例如,如果“主题”输入为空,我希望将其设置为 SELECT 查询仍会返回一行,而不是不返回任何内容

最佳答案

您想要为非空请求参数构建查询子句。

这里是一个Where类,它抽象了where子句的构建。

<?php

class Where {
    private $values;
    private $types;

    static $VALUE_TYPES = [
        'string' => 's',
        'integer' => 'i',
        'double' => 'd',
        'blob' => 'b',
    ];

    function __construct()
    {
        $this->values = [];
        $this->types = '';
    }

    function addCondition($column, $operator, $value) 
    {
        if(!empty($value)) {
            $this->values["$column $operator ?"] = $value;
            $this->types .= static::$VALUE_TYPES[gettype($value)];
        }
        return $this;
    }

    function clause() 
    {
       $condition = join(' AND ', array_keys($this->values));
       if ($condition) {
           return "WHERE $condition";
       }
       return "";
    }

    function params()
    {
        return array_merge([$this->types], array_values($this->values));
    }
}

要使用此类,您需要初始化 Where,然后添加条件。

$where = new Where();
$where->addCondition('input', '=', $input);
$where->addCondition('topic', '=', $topic);
$where->addCondition('location', '=', $location);

以这种方式将子句附加到查询。

echo "SELECT * FROM search {$where->clause()}\n";

然后将参数绑定(bind)到查询语句。

call_user_func_array($stmt->bind_param, $where->params());

关于PHP - 查询空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50436234/

相关文章:

php - 有没有简单的方法可以将数据库表字段中的单词与 soundex 匹配?

MySql 报告按位置和一天中的时间分组

mysql - 左连接,返回不匹配的行,右表上的where子句,分组依据

sql - 检查选择查询在 SQL Server 存储过程中是否有结果

php - Apache ErrorDocument 指令不重定向

php - 如何将特定标签从 RSS XML 导入 MySQL 数据库

php - 创建表时获取语法

c++ - OpenCv/C++ - 轻松从具有大数据库的图片中找到相似之处

php - 在 MySQL 表中使用掩码

MySQL 查询错误 1054