要在MySQL中使用PHP实现模糊匹配以实现自动完成,您可以使用以下步骤:
<form action="search.php" method="post">
<input type="text" name="search" id="search" placeholder="搜索公司名称">
<button type="submit">搜索</button>
</form>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// 检查连接
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$search = $_POST['search'];
$sql = "SELECT company_name FROM companies WHERE company_name LIKE '%$search%'";
$result = $conn->query($sql);
$companies = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$companies[] = $row["company_name"];
}
} else {
echo "未找到相关公司";
}
$conn->close();
<!-- 在HTML文件中添加一个div用于显示自动完成结果 -->
<div id="suggestions"></div>
<!-- 添加jQuery库和自定义的JavaScript代码 --><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script><script>
$(document).ready(function(){
$("#search").on("keyup", function() {
var search = $(this).val();
$.ajax({
type: "POST",
url: "search.php",
data: {search: search},
success: function(data) {
$("#suggestions").html(data);
}
});
});
});
</script>
if (!empty($companies)) {
$output = "<ul>";
foreach($companies as $company) {
$output .= "<li>" . $company . "</li>";
}
$output .= "</ul>";
echo $output;
}
现在,当用户在输入框中输入公司名称时,页面将显示与输入内容匹配的公司名称列表,以实现自动完成功能。
领取专属 10元无门槛券
手把手带您无忧上云