我想创建一个像 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/