动态搜索SQL表并使用PHP和JavaScript在HTML上显示

问题描述 投票:0回答:2

我有一个表单,我希望用户从 SQL 表中选择一个组织,提交表单时,所选组织的 ID 应保存到另一个表中。我在网上和SO上进行了研究,这就是我现在所拥有的。但它不起作用。怎么了? Newbrand.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>";
    }
}
}
?>
javascript php html mysql sql
2个回答
0
投票

问题出在您的查询上。它不是传递

$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)) {

}

参考:mysqli SELECT 与准备好的语句


-1
投票

我在网上搜索了这个功能,发现了这个。我复制了你的来源并让它像这样工作:

$search = "(SELECT `Organization_Name` FROM `organizations_info` WHERE `Organization_Name` LIKE '%". $search_term . "%'  LIMIT 0, 5) ";

正如你所看到的,我更改了 '%". $search_term . "%' ,因为你不能只将字符串放在 sql 查询中的 "" 之间,你必须将它切成碎片,希望你现在明白了。我不经常访问这个网站,所以如果您能将问题解决到 [email protected],如果您给我发一封邮件,那就太好了,希望收到您的来信,祝您好运。

© www.soinside.com 2019 - 2024. All rights reserved.