我在我的网站上的搜索模块遇到了一些问题。我正在使用这段代码:
if(!isset($_POST['search'])) {
$query = "SELECT id, title FROM cars ORDER BY id LIMIT ? OFFSET ?";
}
if(isset($_POST['search']) && $_POST['categories'] != "all") {
$query = "SELECT id, title FROM cars WHERE title LIKE CONCAT(?, '%') ESCAPE '+' AND category = ? ORDER BY id LIMIT ? OFFSET ?";
}
if(isset($_POST['search']) && $_POST['categories'] == "all") {
$query = "SELECT id, title FROM cars WHERE title LIKE CONCAT(?, '%') ESCAPE '+' ORDER BY id LIMIT ? OFFSET ?";
}
try {
$stmt = $db->prepare($query);
if(!isset($_POST['search'])) {
$stmt->bindValue(1, (int) $limit, PDO::PARAM_INT);
$stmt->bindValue(2, (int) $offset, PDO::PARAM_INT);
}
if(isset($_POST['search']) && $_POST['categories'] != "all") {
$search= str_replace(array('+', '%', '_'), array('++', '+%', '+_'), $_POST['search']);
$stmt->bindValue(1, $search, PDO::PARAM_STR);
$stmt->bindValue(2, (int) $_POST['categories'], PDO::PARAM_INT);
$stmt->bindValue(3, (int) $limit, PDO::PARAM_INT);
$stmt->bindValue(4, (int) $offset, PDO::PARAM_INT);
}
if(isset($_POST['search']) && $_POST['categories'] == "all") {
$search= str_replace(array('+', '%', '_'), array('++', '+%', '+_'), $_POST['search']);
$stmt->bindValue(1, $search, PDO::PARAM_STR);
$stmt->bindValue(2, (int) $limit, PDO::PARAM_INT);
$stmt->bindValue(3, (int) $offset, PDO::PARAM_INT);
}
$stmt->execute();
}
catch(PDOException $ex) {
die("Failed to run query: " . $ex->getMessage());
}
$cars = $stmt->fetchAll();
我的搜索表单如下所示:
<input name="search" type="text" size="20" maxlength="20" />
<select name="categories">
<option value="all">All Categories</option>
<option value="1">Free</option>
<option value="2">In use</option>
<option value="3">Damaged</option>
</select>
在汽车表中,每个标题如下所示: 2009 Porsche 911 (year make model) 当我搜索时,如果我不填写搜索框,它可以正常工作,即使我搜索 2009 也可以,但如果搜索保时捷,我没有得到任何结果。这是为什么?我的代码有什么问题?