【发布时间】:2015-01-27 03:36:14
【问题描述】:
我已经搜索了互联网,但我找不到像我的问题一样的东西。我正在尝试构建一个可以从多个表中提取数据的实时搜索功能。它适用于一张桌子,但我希望能够从乐队、用户(专辑等)中提取。
这是我的 PHP 代码:
require ("includes/config/config.php");
$search_term = sanitize(htmlentities($_POST['search_term']));
if (!empty($search_term)){
$search = "(SELECT `band_id`, `band_name` FROM `bands` WHERE `band_name` LIKE '%$search_term%' LIMIT 0, 5)
UNION ALL
(SELECT `user_id`, `username` FROM `users` WHERE `username` LIKE '%$search_term%' LIMIT 0, 5)";
$query = mysqli_query($conn, $search);
$result = mysqli_num_rows($query);
while ($row = mysqli_fetch_assoc($query)){
#$user_id = $row['user_id'];
#$username = $row['username'];
$band_id = $row['band_id'];
$band_name = $row['band_name'];
$check = mysqli_num_rows($query);
if ($check != 0){
echo "<a style='text-decoration: none; color: black;' href='index.php?band=$band_id'><li class='searchResults'>" . ucfirst($band_name) . "</li></a>";
} else {
echo "<li class='searchResults'>No Results Found</li>";
}
}
}
jQuery:
$("#searchbar").keyup(function(){
var searchTerm = $(this).val();
$.post('search.php', { search_term: searchTerm}, function(data){
$(".searchResults").html(data);
$("#searchUl").css("display", "block");
});
});
同样,其他一切都运行良好,但我不知道如何以某种方式查询多个表,因此我可以以不同的方式回显 href(即 index.php?band=$band_id for band 和 index.php?user =用户的$user_id。
【问题讨论】: