我在 PDO 中成功连接到我的 MySQL 数据库,目前我正在尝试让它在数据库中查询类似搜索查询的项目。
<?php
include ('connection.php');
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM entries WHERE name LIKE :searchq or description LIKE :searchq or content LIKE :searchq";
global $conn;
$stmt = $conn->prepare($sql);
$stmt->bindParam(":searchq",$searchq,PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
if($count == 0) {
$output = 'No results found, buddy.';
} else {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$elvl = $row['level'];
$ehp = $row['hp'];
$output .= '<tr><td><a href="http://ccc.aaaa.whatever/' .$eName. '" onclick="document.linkform.submit();">'.$eName.'</a></td><td>'.$eDesc.'</td><td>'.$elvl.'</td><td>'.$ehp.'</td></tr>';
}
}
return $output;
}
}
?>
我正在努力让它被搜索。除非查询仅与名称完全匹配,否则不会显示任何结果。
最佳答案
除非特别指示,LIKE
运算符不会进行部分匹配。也许您想在搜索字符串前添加/附加 %
通配符:
$searchq = '%' . $searchq . '%';
关于php - MySQL之类的查询不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22265478/