php中实现搜索
PHP 实现搜索功能
在 PHP 中实现搜索功能通常涉及数据库查询、表单处理和结果展示。以下是几种常见的实现方式:
基础数据库搜索
使用 MySQL 或其他数据库的 LIKE 运算符实现简单搜索:
$searchTerm = $_GET['search'] ?? '';
if (!empty($searchTerm)) {
$query = "SELECT * FROM products WHERE name LIKE '%$searchTerm%'";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_assoc($result)) {
echo $row['name'] . "<br>";
}
}
预处理语句防止 SQL 注入
更安全的做法是使用预处理语句:
$searchTerm = $_GET['search'] ?? '';
if (!empty($searchTerm)) {
$stmt = $connection->prepare("SELECT * FROM products WHERE name LIKE ?");
$searchParam = "%$searchTerm%";
$stmt->bind_param("s", $searchParam);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['name'] . "<br>";
}
}
全文索引搜索
对于更高效的文本搜索,可以使用 MySQL 的全文索引:
$searchTerm = $_GET['search'] ?? '';
if (!empty($searchTerm)) {
$query = "SELECT * FROM products
WHERE MATCH(name, description) AGAINST(? IN BOOLEAN MODE)";
$stmt = $connection->prepare($query);
$stmt->bind_param("s", $searchTerm);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo $row['name'] . "<br>";
}
}
前端搜索表单
HTML 表单示例:
<form method="GET" action="search.php">
<input type="text" name="search" placeholder="搜索...">
<button type="submit">搜索</button>
</form>
高级搜索选项
实现多条件搜索:
$name = $_GET['name'] ?? '';
$category = $_GET['category'] ?? '';
$minPrice = $_GET['min_price'] ?? 0;
$conditions = [];
$params = [];
$types = '';
if (!empty($name)) {
$conditions[] = "name LIKE ?";
$params[] = "%$name%";
$types .= 's';
}
if (!empty($category)) {
$conditions[] = "category_id = ?";
$params[] = $category;
$types .= 'i';
}
if (!empty($minPrice)) {
$conditions[] = "price >= ?";
$params[] = $minPrice;
$types .= 'd';
}
$query = "SELECT * FROM products";
if (!empty($conditions)) {
$query .= " WHERE " . implode(" AND ", $conditions);
}
$stmt = $connection->prepare($query);
if (!empty($params)) {
$stmt->bind_param($types, ...$params);
}
$stmt->execute();
使用搜索引擎
对于大型网站,可以集成 Elasticsearch 或 Algolia 等专业搜索引擎:
// Elasticsearch 示例
$client = Elasticsearch\ClientBuilder::create()->build();
$params = [
'index' => 'products',
'body' => [
'query' => [
'match' => [
'name' => $_GET['search']
]
]
]
];
$response = $client->search($params);
foreach ($response['hits']['hits'] as $hit) {
echo $hit['_source']['name'] . "<br>";
}
分页处理
搜索结果分页实现:
$page = $_GET['page'] ?? 1;
$limit = 10;
$offset = ($page - 1) * $limit;
$query = "SELECT * FROM products WHERE name LIKE ? LIMIT ? OFFSET ?";
$stmt = $connection->prepare($query);
$searchParam = "%$searchTerm%";
$stmt->bind_param("sii", $searchParam, $limit, $offset);
$stmt->execute();
根据具体需求选择合适的实现方式,小型网站可以使用简单的数据库查询,而大型项目可能需要专业搜索引擎解决方案。







