Я хочу создать форму, как в этом сообщении, но я хочу сделать так, чтобы, если один из входов пуст, php все равно обрабатывает запросы. Я использую INNERJOIN
или LEFTJOIN
?
EDIT: Это 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
прежнему возвращал строку вместо ничего
Использование PDO для лучшей гибкости для этой задачи. В приведенном ниже коде также используются инструкции if else для построения необходимого запроса.
Обновленный код:
$db = new PDO('mysql:host=localhost;dbname=dbnme', 'root','password');
$input = $_GET['input'];
$topic = $_GET['topic'];
$location = $_GET['location'];
$sql_string = "SELECT * FROM search";
$where_clause = "";
if($input != ""){
$where_clause .= "input = :input";
}
if($topic != ""){
if($where_clause !="") $where_clause .= " AND ";
$where_clause .= "topic = :topic";
}
if($location != ""){
if($where_clause !="") $where_clause .= " AND ";
$where_clause .= "location = :location";
}
$sql_string = $sql_string.($where_clause!=""?" WHERE ":"").$where_clause;
$stmt = $db->prepare($sql_string);
$stmt->bindParam(':input', $input);
$stmt->bindParam(':topic', $topic);
$stmt->bindParam(':location', $location);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
print_r( $row );
}
Вы хотите создать предложение запроса для непустых параметров запроса.
Вот класс 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";
Затем привяжите params к запросу запроса.
call_user_func_array($stmt->bind_param, $where->params());
left
илиinner
соединением. Пожалуйста, добавьте код, чтобы мы могли видеть, что вы на самом деле делаете.