php实现搜索功能
实现基础搜索功能
使用PHP和MySQL实现基础的搜索功能需要结合表单提交与数据库查询。创建一个HTML表单用于接收用户输入的搜索关键词,通过PHP处理表单数据并查询数据库。
// 搜索表单 (HTML部分)
<form method="GET" action="search.php">
<input type="text" name="keyword" placeholder="输入搜索关键词">
<button type="submit">搜索</button>
</form>
// 处理搜索 (PHP部分 - search.php)
$keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';
if (!empty($keyword)) {
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$stmt = $db->prepare("SELECT * FROM articles WHERE title LIKE :keyword OR content LIKE :keyword");
$stmt->execute([':keyword' => "%$keyword%"]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
使用全文索引提高效率
对于大型数据库,LIKE查询效率较低。MySQL的全文索引(FULLTEXT)能显著提升文本搜索性能,特别适用于文章内容等长文本搜索。

-- 创建全文索引 (MySQL)
ALTER TABLE articles ADD FULLTEXT(title, content);
// 使用全文索引查询
$stmt = $db->prepare("
SELECT * FROM articles
WHERE MATCH(title, content) AGAINST(:keyword IN BOOLEAN MODE)
");
$stmt->execute([':keyword' => $keyword]);
实现分页功能
搜索结果较多时,分页功能必不可少。结合LIMIT和OFFSET实现数据分页显示。
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 10;
$offset = ($page - 1) * $perPage;
$stmt = $db->prepare("
SELECT SQL_CALC_FOUND_ROWS * FROM articles
WHERE MATCH(title, content) AGAINST(:keyword)
LIMIT :offset, :perPage
");
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->bindValue(':perPage', $perPage, PDO::PARAM_INT);
$stmt->execute([':keyword' => $keyword]);
$total = $db->query("SELECT FOUND_ROWS()")->fetchColumn();
$totalPages = ceil($total / $perPage);
添加搜索建议功能
使用AJAX实现实时搜索建议可以提升用户体验。当用户输入时,前端通过AJAX请求获取搜索建议。

// 前端JavaScript
document.getElementById('search-input').addEventListener('input', function() {
fetch(`suggest.php?term=${encodeURIComponent(this.value)}`)
.then(response => response.json())
.then(data => showSuggestions(data));
});
// suggest.php
$term = $_GET['term'] ?? '';
$stmt = $db->prepare("
SELECT title FROM articles
WHERE title LIKE :term
LIMIT 5
");
$stmt->execute([':term' => "%$term%"]);
echo json_encode($stmt->fetchAll(PDO::FETCH_COLUMN));
高级搜索功能实现
对于复杂需求,可以实现多条件组合搜索,包括分类筛选、日期范围等高级搜索选项。
// 构建动态SQL查询
$conditions = [];
$params = [];
if (!empty($_GET['keyword'])) {
$conditions[] = "MATCH(title, content) AGAINST(:keyword)";
$params[':keyword'] = $_GET['keyword'];
}
if (!empty($_GET['category'])) {
$conditions[] = "category_id = :category";
$params[':category'] = $_GET['category'];
}
if (!empty($_GET['start_date'])) {
$conditions[] = "publish_date >= :start_date";
$params[':start_date'] = $_GET['start_date'];
}
$sql = "SELECT * FROM articles";
if (!empty($conditions)) {
$sql .= " WHERE " . implode(" AND ", $conditions);
}
$stmt = $db->prepare($sql);
$stmt->execute($params);
搜索结果高亮显示
在搜索结果中高亮显示匹配关键词,提升结果可读性。
function highlightKeyword($text, $keyword) {
return preg_replace(
"/(" . preg_quote($keyword, '/') . ")/i",
'<span class="highlight">$1</span>',
$text
);
}
// 在输出结果时调用
foreach ($results as $result) {
echo highlightKeyword($result['title'], $keyword);
echo highlightKeyword($result['content'], $keyword);
}





