我有一个表单,我希望用户从 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
的值,而是将其作为字符串传递。您可能希望使用准备好的语句并首先绑定(bind)参数:
$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)) {
}
关于javascript - 使用 PHP 和 JavaScript 动态搜索 SQL 表并在 HTML 上显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36683870/