简体   繁体   English

需要有关使用MySQL查询PDO的下拉结果的搜索栏的帮助

[英]Need help about Search Bar with dropdown result using mysql query PDO

I have search bar on my facebox. 我的面板上有搜索栏。 It will search for the lastName or firstName every time the user will input a character or name in the textbox. 每次用户在文本框中输入字符或名称时,它将搜索lastName或firstName。

For more clarification here's the screenshot: 有关更多说明,请参见屏幕截图:

在此处输入图片说明

and here's the code: 这是代码:

UPDATE UPDATE

This is the code I found in the web on those 3 days of in-activity 这是我在闲置的三天里在网上找到的代码

this code made by Malik Naik (I modified some of his code) Malik Naik编写的这段代码(我修改了他的一些代码)

addBookRecord.php addBookRecord.php

<?php
session_start();
$recordType = $_GET['status'];  
?>
<!-- this code made by Malik Naik -->
<script>
function searchResult(string){
    var xmlhttp;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else{
        xmlhttp = new ActiveXObject("XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            document.getElementById("result").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "search.php?search="+string, true);
    xmlhttp.send(null);
}
</script>

<style>
    #result{
        width: 350px; margin: 0 auto; max-height: 150px; overflow: hidden;
    }
</style>

 <!DOCTYPE html> <html lang="en"> <head> <!--<link rel="stylesheet" type="text/css" href="../css/bootstrap.min.css">--> <link rel="stylesheet" type="text/css" href="../css/bootstrap-glyphicons.css"> </head> <span style="color:#B22222"><strong>Add Record</strong></span> <form action = "" method="post"> <div style="margin-top: 10px; margin-left: 10px;"> <strong>Name:</strong> <!--<form name="form1" method="post">--> <div class="input-group stylish-input-group"> <input type="text" class="form-control" name="searchStud" placeholder="Search" onkeydown="searchResult(this.value)" autocomplete="off"> <span class="input-group-addon"> <span class="glyphicon glyphicon-search"></span> </span> </div> <div id="result"></div> <!--</form>--> <?php if ($recordType=='book'){ ?> <strong>Item:</strong><br> <input type="text" name="addBookItem" value="e-math (K to 12)"> <input type="text" name="searchID" value="<?php echo $_SESSION['addBorrowID'];?>"><br> <strong>Description:</strong> <br> <input type="text" name="addBookDescription" value="Worktext in Mathematics"><br> <strong>Author:</strong> <br> <input type="text" name="addBookAuthor" value="Orlando A. Orence & Marilyn O. Mendoza"><br> <strong>Publisher:</strong> <br> <input type="text" name="addBookPublisher" value="REX Book Store"><br> <strong>ISBN:</strong> <br> <input type="text" name="addBookISBN" value="9789712361982"><br> <?php } else{ ?> <strong>Item:</strong> <br> <input type="text" name="addBookItem" value="e-math (K to 12)"><br> <strong>Model:</strong> <br> <input type="text" name="addBookAuthor" value="Orlando A. Orence & Marilyn O. Mendoza"><br> <strong>Serial:</strong> <br> <input type="text" name="addBookPublisher" value="REX Book Store"><br> <?php } ?> <br> </div> <button class="btn btn-success btn-block btn-large" name="addRecordButton" >Save Changes</button> </form> 

search.php search.php中

<?php
session_start();
include("../db/dbCon.php");

if(isset($_GET['search']) && $_GET['search'] != ''){
    $search=$_GET['search'];
    $qry = $conn->prepare("
                            SELECT e.enrld_id, CONCAT(i.lastName,', ', i.firstName,' ',i.middleName)
                            AS fullName
                            FROM user_info i
                            JOIN enrolled e ON e.userID=i.userID 
                            WHERE i.lastName LIKE '%$search%' OR i.firstName LIKE '%$search%'
                        ");
    $qry->execute();
    $result = $qry->fetchAll(PDO::FETCH_ASSOC); 
    foreach($result as $row){
        if ($row['enrld_id']!=0){
                //$_SESSION['addBorrowID']=(int)$row['enrld_id'];
                $fullName = $row['fullName'];
                echo '<div id="result" onclick="getSearchID("'.$row['enrld_id'].'")">'.$fullName.'</div>';
        }
    }
}

?>

<?php
    function getSearchID($enrldID){
        $_SESSION['addBorrowID'] = $enrldID;
    }
?>

This scenario is just to test if the $_SESSION['addBorrowID'] has a value 此方案只是为了测试$ _SESSION ['addBorrowID']是否具有值

if (isset($_POST['addRecordButton'])){
echo '<script type="text/javascript">alert("'.$_SESSION['addBorrowID'].'");</script>';
}

MAIN QUESTION 主要问题

My problem is I can't store the enrld_id in the searchID textbox whenever I click the result below the search bar... I use the Mouse event but it's not working: 我的问题是,每当我单击搜索栏下方的结果时,都无法将enrld_id存储在searchID文本框中...我使用Mouse事件,但无法正常工作:

foreach($result as $row){
        if ($row['enrld_id']!=0){
                //$_SESSION['addBorrowID']=(int)$row['enrld_id'];
                $fullName = $row['fullName'];
                echo '<div id="result" onclick="getSearchID("'.$row['enrld_id'].'")">'.$fullName.'</div>';
        }
    }

<?php
function getSearchID($enrldID){
    $_SESSION['addBorrowID'] = $enrldID;
}
?>

but the result is empty. 但结果为空。 I want to pass the value of $_SESSION['addBorrowID'] to this textbox 我想将$ _SESSION ['addBorrowID']的值传递给此文本框

在此处输入图片说明

------- END ------- - - - - 结束 - - - -

this is OPTIONAL to answer 这是可选的

Here is my little question: 这是我的小问题:

How can I prevent an SQL injection using a LIKE query? 如何防止使用LIKE查询进行SQL注入? I know how to use bindParam but I don't know if my theory is right: 我知道如何使用bindParam但是我不知道我的理论是否正确:

lastName LIKE '%?%' OR firstName LIKE '%?%'");
$qry->bindParam(1, $find);
$qry->bindParam(2, $find);

Is this right? 这是正确的吗?

ANSWER TO PRIMARY QUESTION 回答主要问题

Here is the problem that you're running into. 这是您遇到的问题。 You're trying to connect front-end code with server-side code in a way that does not work. 您正在尝试以无法正常工作的方式将前端代码与服务器端代码连接起来。 Server side code processes the PHP and then hands the resulting code to the browser. 服务器端代码处理PHP,然后将结果代码传递给浏览器。 At this point only front-end or client-side code is available. 此时,只有前端或客户端代码可用。 This is the code snippet that I'm talking about: 这是我正在谈论的代码片段:

<?php
session_start();
include("../db/dbCon.php");

if(isset($_GET['search']) && $_GET['search'] != ''){
    $search=$_GET['search'];
    $qry = $conn->prepare("
                            SELECT e.enrld_id, CONCAT(i.lastName,', ', i.firstName,' ',i.middleName)
                            AS fullName
                            FROM user_info i
                            JOIN enrolled e ON e.userID=i.userID 
                            WHERE i.lastName LIKE '%$search%' OR i.firstName LIKE '%$search%'
                        ");
    $qry->execute();
    $result = $qry->fetchAll(PDO::FETCH_ASSOC); 
    foreach($result as $row){
        if ($row['enrld_id']!=0){
                //$_SESSION['addBorrowID']=(int)$row['enrld_id'];
                $fullName = $row['fullName'];
                echo '<div id="result" onclick="getSearchID("'.$row['enrld_id'].'")">'.$fullName.'</div>';
        }
    }
}

?>

<?php
    function getSearchID($enrldID){
        $_SESSION['addBorrowID'] = $enrldID;
    }
?>

You're adding an onclick="getSearchId... but your defining the function in <?php ... >? tags. This is no longer accessible by the time the page is delivered to the browser. If you have time and see yourself doing a lot of front end development I would highly recommend taking thie quick course ; it will save you a lot of headaches and is great investment. This problem would be become apparent if you had checked the HTML on the page, so forth and so on. At the top of your code I see you've included a very barebones AJAX call. you'll want to utilize something like that in this case... Here is a rough idea of what you'll want to do. 您要添加onclick="getSearchId...但是您要在<?php ... >?标签中定义函数。当页面交付给浏览器时,将无法再访问该函数。您自己需要做很多前端开发,所以我强烈建议您快速学习 ;它可以为您省去很多麻烦,并且是一笔巨大的投资。在代码的顶部,我看到您包括了一个非常准系统的AJAX调用,在这种情况下,您将想要利用类似的东西……这是您想要做的一个大概想法。

<script>
    var xmlhttp;
    function ajaxCall (string, callback) {
        if(window.XMLHttpRequest){
            xmlhttp = new XMLHttpRequest();
        }else{
            xmlhttp = new ActiveXObject("XMLHTTP");
        }
        xmlhttp.onreadystatechange = callback
        xmlhttp.open("GET", , true);
        xmlhttp.send(null);
    }

    function searchResult(string){
        ajaxCall("search.php?search="+string, function(){
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                document.getElementById("result").innerHTML = xmlhttp.responseText;
            }
        });
    }

    function getSearchId(id) {
        ajaxCall( 'path_to_php_file_that_returns_search_id?searchId=' + id, function() {
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                //code here to put the id in the right spot
            }
        });
    }
</script>

This will be the file_that_returns_search_id.php 这将是file_that_returns_search_id.php

<?php
    session_start();
    echo $_SESSION['addBorrowID'] = $_GET['searchId'];

Now that I look at this, I have no idea what you're trying to accomplish. 现在我看了一下,我不知道您要完成什么。 This looks a lot more like a setting of searchId, but I'm just going off what's here. 这看起来更像是searchId的设置 ,但是我只是在讲这里的内容。

ANSWER TO OPTIONS QUESTION 回答选项问题

Am I reading this right? 我读对了吗? Does 99% of this stuff not have to do with your question? 这些资料中有99%是否与您的问题无关? I feel like it's one of the trick questions where they tell you several exchanges of people getting on and off a bus and then ask you how old the bus driver is. 我觉得这是一个棘手的问题,他们告诉您几次上下车的人往来,然后问您公交车司机的年龄。

If I'm right your question only needed this part: 如果我是对的,您的问题只需要这一部分:

$qry = $conn->prepare("
                    SELECT userID, lastName, firstName, middleName
                    FROM user_info WHERE lastName LIKE '%".$find."%' OR firstName LIKE '%".$find."%'
                ");
$qry->execute();

To answer your question. 回答您的问题。 I'm going to assume that your $conn variable is using PDO to query the database. 我将假设您的$conn变量正在使用PDO查询数据库。 If that's the case then the information you're looking for is here . 如果是这种情况,那么您正在寻找的信息就在这里 But your new code could look something like this. 但是您的新代码可能看起来像这样。

$qry = $conn->prepare(
  "SELECT userId, lastName, FirstName, MiddleName
  FROM user_info where lastName LIKE '%?%' OR firstName LIKE '%?%'"
);

$qry->execute([$find, $find]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM