我在搜索控制器中使用此搜索功能将搜索结果发送到网页。由于某种原因,它不起作用。我使用PDO,我也无法在php日志中看到任何错误。我花了很多时间试图找出错误的原因并且看起来好像失去了原因
public function search($search_string){
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$sql = 'SELECT * FROM products WHERE name LIKE "%:search%" OR description LIKE "%:search%"';
$query = $this->db->prepare($sql);
$query->execute(array(':search' => $search_string));
$this->search=$query->fetchAll();
// Do Search
// Check If We Have Results
if (isset($query)) {
foreach($this->search as $key => $value) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $value->name);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $value->name);
$display_url = 'http://hello.com/what'.urlencode($value->name).'&lang=en';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Function
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}
}
答案 0 :(得分:0)
更改此部分:
$sql = 'SELECT * FROM products WHERE name LIKE "%:search%" OR description LIKE "%:search%"';
$query = $this->db->prepare($sql);
$query->execute(array(':search' => $search_string));
为:
$sql = 'SELECT * FROM products WHERE name LIKE :search OR description LIKE :search';
$query = $this->db->prepare($sql);
$query->execute(array(':search' => "%".$search_string."%"));
您使用占位符的方式无效。