我正在尝试在PHP中创建一个搜索功能,但遇到了一个小问题。当我输入单个搜索词时,我得到预期的结果(列出单个记录,单个搜索结果),但是当我输入2个或更多有效搜索词时,我会多次列出相同的记录。有人可以指出我出错的地方吗?
public function product_search($search_terms)
{
$search_terms = htmlspecialchars($search_terms);
$search_terms = stripslashes($search_terms);
$search_terms_array = explode(" ", $search_terms);
$terms_count = count($search_terms_array);
$zerocount = 0;
for($i = 0; $i < $terms_count; $i++)
{
$search_terms_array = trim($search_terms_array[$i]);
${"query".$i} = $this->mysqli_link->query("SELECT * FROM sjs_product_list WHERE prod_tags LIKE '%" . $search_terms_array[$i] . "%'");
if(${"query".$i}->num_rows < 1)
{
$zerocount++;
}
else
{
while($row = ${"query".$i}->fetch_array())
{
$rows[] = $row;
}
foreach($rows as $row)
{
echo "<h3><a href=\"index.php?section=products&subsection=" . $row['prod_category'] . "&prodid=" . $row['prod_id'] . "\">" . $row['prod_name'] . "</h3></a><img src=\"includes/images/product_images/" . $row['prod_category'] . "/" . $row['prod_pic_filename'] . "\" alt=\"\"/><p>Price: " . $row['prod_price'] . "</p><p>" . $row['prod_code'] . "</p>";
}
}
}
if($zerocount == $terms_count)
{
echo "<h3>Your search terms returned 0 results. Please try using different search terms.";
}
}
答案 0 :(得分:0)
更改
$search_terms_array = trim($search_terms_array[$i]);
到
$search_terms_array[$i] = trim($search_terms_array[$i]);
你用第一个元素替换了整个数组。然后,当你在此之后使用$search_terms_array[$i]
时,你只是得到了这个字符串的i
字符。
另一个问题:每次循环时你都没有清除$rows
数组。放:
$rows = array();
之前
while ($row = ${"query".$i}->fetch_array())
您在循环中打印整个$rows
数组,因此每次打印上一次迭代中的行时,即使它们已经打印过。
答案 1 :(得分:0)
在代码中替换以下两行: -
<?php
$search_key = trim($search_terms_array[$i]);
${"query".$i} = $this->mysqli_link->query("SELECT * FROM sjs_product_list WHERE prod_tags LIKE '%" . $search_key . "%'");
?>