您好我试图在php中编写搜索功能,但我总是得到0结果。
<?php
$mysqli = new mysqli('localhost', 'root', 'testing123', 'test')
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//collect
$output = '';
if(isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($mysqli, "SELECT * FROM Users WHERE UsernameLIKE '%$searchq%'");
$count = mysqli_num_rows($query);
// if the $result contains at least one row
if ($query->num_rows > 0) {
// output data of each row from $result
while($row = $query->fetch_assoc()) {
}
}
else {
echo '0 results';
}
}
?>
任何想法如何解决?
编辑1.即使这被注释,这仍然不允许它被解决。
if(!empty($_POST['search'])){
$searchq = $_POST['search'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($mysqli, "SELECT * FROM Users WHERE Username LIKE '$searchq%'");
$count = mysqli_num_rows($query);
// if the $result contains at least one row
if ($query->num_rows > 0) {
// output data of each row from $result
while($row = $query->fetch_assoc()) {
}
}
else {
echo '0 results';
}
}
答案 0 :(得分:1)
为了匹配学校,学校名称或学校名称1
您的查询需要读取并删除起始%
并保留尾随%
WHERE SchoolName LIKE '$searchq%'"
现在,它找不到学校名称和学校名称1的原因是因为它包含空格而你的正则表达式正在替换那些空格。
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
通过评论,您可以恢复使用:
WHERE SchoolName LIKE '%$searchq%'"