我尝试搜索产品时遇到一些问题,用户可以选择点击完整搜索或部分搜索。问题是,当用户点击完整搜索并输入内容时,整个表格打印出来并且产品的单词不是(我想要打印出产品而不是整个表格)并且通过部分搜索,它只是打印它没有找到匹配。下面是我目前的代码:
// DB configuration //
if (!isset($_POST["searchtype"])) {
echo "<form method='POST'>";
echo "Search for product:<br>";
# using html5 input type search
echo "<input type='text' name='searchtext' size='15' placeholder='search' results='5' autosave='saved-searches'>";
echo "<br><br>";
echo "Full search";
echo"<input type='radio' value='FULL' checked name='searchtype'><br>";
echo "Partial search ";
echo "<input type='radio' name='searchtype' value='PARTIAL'>";
echo "<br><br>";
echo "<input type='submit' value='Search' name='submit'>";
echo "</form>";
}
else {
$searchtext = $_POST["searchtext"]; # Retrieve from the form
$searchtype = $_POST["searchtype"]; # Retrieve from the form
$searchtext_san = sanitize_form_text($searchtext); # Prevents SQL injections!
try{
if($DBH == null)
$DBH = new PDO($dsn, $dbuser, $dbpass);
$sql = "select name, price, details from products where name='$searchtext_san'";
if ($searchtype == "FULL"){
$sql .= " = :searchtext_san";
$STH = $DBH->prepare($sql);
$STH->execute(array(':searchtext_san' => $searchtext_san));
}
if ($searchtype == "PARTIAL"){
$sql .= " LIKE ':searchtext_san'";
$STH = $DBH->prepare($sql);
$STH->execute(array(':searchtext_san' => '%'.$searchtext_san.'%'));
}
$STH->setFetchMode(PDO::FETCH_ASSOC);
$total = $STH->rowCount();
if ($total == 0){
echo "Sorry, no matches found!";
}
if ($total > 0){
while ($row = $STH->fetch()){
echo "{$row["name"]} {$row["price"]} {$row["details"]}<br>";
}
}
$DBH = null;
}
catch (PDOException $e){
echo '<b>PDOException: </b>',$e->getMessage();
die();
}
}
function sanitize_form_text($t)
{
$t = strip_tags($t);
$t = ereg_replace("[^A-Za-z0-9@._-]", "", $t);
return $t;
}
?>
答案 0 :(得分:0)
尝试使用全文搜索
SELECT * FROM articles WHERE MATCH (title,body)
AGAINST ('+MySQL -YourSQL' IN BOOLEAN MODE);
对于部分搜索,您可以like
SELECT name FROM products WHERE name RLIKE '[yourtext]'