[英]Dynamically search SQL table and display on HTML using PHP and JavaScript
我有一个表单,我希望用户从 SQL 表中选择一个组织,并且在提交表单时,所选组织的 ID 应保存到不同的表中。 我在网上和 SO 上进行了研究,这就是我现在所拥有的。 它不起作用。 怎么了? 新品牌.php:
<form action="newbrand.php" method="post">
Brand Name: <input type="text" name="bname" /><br><br>
Ogranization: <input type="text" name="searchbar" id="searchbar"><br><br>
<script>
$("#searchbar").keyup(function(){
var searchTerm = $(this).val();
$.post('search.php', { search_term: searchTerm}, function(data){
$(".searchResults").html(data);
$("#searchUl").css("display", "block");
});
});
</script>
Organization ID: <input type="hidden" name="gid" value="" /><br><br>
Gallery ID: <input type="text" name="gid" /><br><br>
</form>
搜索.php:
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
$search_term = sanitize(htmlentities($_POST['search_term']));
if (!empty($search_term)){
$search = "(SELECT `Organization_Name` FROM `organizations_info` WHERE `Organization_Name` LIKE '%$search_term%' LIMIT 0, 5) ";
$query = mysqli_query($link, $search);
$result = mysqli_num_rows($query);
while ($row = mysqli_fetch_assoc($query)){
#$user_id = $row['user_id'];
#$username = $row['username'];
$orgname = $row['Organization_Name'];
$check = mysqli_num_rows($query);
if ($check != 0){
echo "<a style='text-decoration: none; color: black;' href='newbrand.php?band=$orgname'><li class='searchResults'>" . ucfirst($orgname) . "</li></a>";
} else {
echo "<li class='searchResults'>No Results Found</li>";
}
}
}
?>
问题出在您的查询上。 它不是传递$search_term
的值,而是将其作为字符串传递。 您可能希望使用准备好的语句并首先绑定参数:
$stmt = mysqli_prepare($link, "SELECT `Organization_Name` FROM `organizations_info` WHERE `Organization_Name` LIKE ? LIMIT 0, 5");
mysqli_stmt_bind_param($stmt, "s", "%{$search_term}%");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $organizaton_name);
while (mysqli_stmt_fetch($stmt)) {
}
我在网上搜索了这个功能并找到了这个。 我复制了你的源代码并让它像这样工作:
$search = "(SELECT Organization_Name
FROM organizations_info
WHERE Organization_Name
LIKE '%". $search_term . "%' LIMIT 0, 5) ";
正如你所看到的,我改变了 '%". $search_term . "%' ,因为你不能把字符串放在 "" 之间的 sql 查询中,你必须把它切成碎片,希望你现在明白了。 我不经常访问这个网站,所以如果你把问题解决了,给我发一封邮件给 sceptdekkheroes@gmail.com 会很酷,希望收到你的来信,祝你好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.