php html 搜索中如何带多个字段搜索,如果是空的则不显示在链接中
时间: 2024-02-28 21:55:06 浏览: 25
你可以在搜索表单中添加多个输入框,每个输入框代表一个要搜索的字段。在提交表单时,收集所有非空的输入框的值,然后将这些值作为查询参数添加到搜索链接中。
以下是一个简单的示例代码:
```html
<form action="search.php" method="get">
<label for="search-title">Title:</label>
<input type="text" id="search-title" name="title">
<label for="search-author">Author:</label>
<input type="text" id="search-author" name="author">
<button type="submit">Search</button>
</form>
```
在提交表单后,你可以使用 PHP 代码收集所有非空的输入框的值,然后将它们添加到搜索链接中:
```php
<?php
$title = $_GET['title'] ?? '';
$author = $_GET['author'] ?? '';
$query_params = [];
if (!empty($title)) {
$query_params['title'] = $title;
}
if (!empty($author)) {
$query_params['author'] = $author;
}
$search_url = 'search.php';
if (!empty($query_params)) {
$search_url .= '?' . http_build_query($query_params);
}
echo "<a href=\"$search_url\">Search</a>";
?>
```
在这个示例中,我们使用了 PHP 的 `$_GET` 变量来收集表单提交后的查询参数。我们还使用了 PHP 7 的 null coalescing 运算符来简化代码。如果 `$_GET['title']` 或 `$_GET['author']` 不存在或为空,我们将它们的值设置为一个空字符串。然后,我们创建了一个空的查询参数数组 `$query_params`,并使用 `if` 语句检查每个输入框的值是否为空。如果不为空,我们将输入框的名称和值添加到 `$query_params` 中。最后,我们使用 `http_build_query()` 函数将查询参数数组转换为 URL 查询字符串,并将其附加到搜索链接中。如果没有查询参数,我们只显示搜索页面的 URL。