【问题标题】:Results from search bar to be links to individual Profiles搜索栏的结果将链接到各个配置文件
【发布时间】:2016-04-17 11:02:28
【问题描述】:

我有一个搜索栏,可以返回成员表中的用户名。但是,我希望结果不是只显示他们的用户名,而是链接到他们的个人资料。

这里是搜索栏的 PHP 代码:

<?php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "coursework_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 

$partialSearch = "%". $_POST['partialSearch'] ."%";
$stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ? 
                    LIMIT 3");

$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($username);

while ($stmt->fetch()) {

echo $username;

echo "<div>".$searchResults."</div>";
}
?>

这是实际的搜索栏,其中结果 div 是 ajax 的目标 div:

<li><input type="text" name="partialSearch"onkeyup="search(this.value)" placeholder="Search for other users"/></li>

<section id="divider">
<div id="results"></div>

ajax:

function search(partialSearch){
$.ajax({url:"searchbar.php",type:"POST",data:{partialSearch:partialSearch},success:function(result){
$("#results").html(result);
}});
};

以下是我用来生成用户配置文件的代码:

<?php

    function user_profile(){

            $servername = "localhost";
            $username = "root";
            $password = "root";
            $dbname = "coursework_db";


            // Create connection
            $conn = new mysqli($servername, $username, $password, $dbname);
            // Check connection
            if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
            } 

            $sql = 'SELECT memberID, username FROM members;';
            $result = $conn->query($sql);

            $users = array();

             while($row = $result->fetch_assoc()) {
                $user[]= $row;
            }

            return $user;

            foreach (user_profile() as $user){
        ?>  
            <p>
            <a href="ViewProfile.php?uid=<?php echo $user['memberID'];?>"><?php echo $user['username'];?></a>
            </p>
        <?php


    }
    }

?>

提前感谢您的帮助。希望得到意见和建议

【问题讨论】:

    标签: php jquery html ajax


    【解决方案1】:

    您已经非常接近完成申请了。我重构了您的代码,并添加了详细的注释来指导您完成更改。

    搜索页面

        <form action="#">
            <input type="text" name="partialSearch" onkeyup="search(this.value)" placeholder="Search for other users"/>
        </form>
    
        <section id="divider">
            <div id="results"></div>
        </section>
    
        <!-- always place scripts just before the ending <body> tag for better performance -->
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script type="text/javascript">
            function search(partialSearch) {
                $.ajax({
                    url: "search_results_ajax.php",
                    type: "POST",
                    data: {partialSearch: partialSearch},
                    success: function (result) {
                        $("#results").html(result);
                    }
                });
            }
        </script>
    

    Ajax 搜索

    <?php
    /**
     * Your function names should match their purpose. user_profile() does not accurately define the operations
     * this function will be performing.
     *
     * @param array $usernameToSearch - The username to compare with the database.
     *
     * @return array - A list of users.
     */
    function get_users_by_username($usernameToSearch)
    {
        $servername = "localhost";
        $username   = "root";
        $password   = "root";
        $dbname     = "coursework_db";
    
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
    
        /**
         * The query below will fetch all of your users from the database.
         *
         *      SELECT memberID, username FROM members
         *
         * You can narrow the results by using the WHERE clause with the LIKE operator:
         *
         *      $sql = 'SELECT memberID, username FROM members WHERE username LIKE "%' . $username . '%"'
         *
         * Learn more about the LIKE clause at: http://www.w3schools.com/sql/sql_like.asp
         */
        $sql    = 'SELECT memberID, username FROM members WHERE username LIKE "%' . $usernameToSearch . '%"';
        $result = $conn->query($sql);
    
        $users = array();
        while($row = $result->fetch_assoc()) {
            /** Renamed from $user to $users to match variable definition. */
            $users[] = $row;
        }
    
        /** Renamed from $user to $users to match variable definition. */
        return $users;
    }
    
    
    /**
     * Your AJAX request sends a parameter called "partialSearch", which contains the value of the textbox
     * on the search page. You can access that parameter through the PHP global, $_POST.
     *
     * (or $_GET, if the parameter is stored in the url. Such as: www.mywebsite.com?partialSearch=my+search+here)
     *
     * Before you execute get_users_by_username(), you must check if the "partialSearch" parameter exists. This
     * can be done through the empty() function, which essentially checks if the value if $_POST['partialSearch'] is:
     *  - false
     *  - an empty string
     *  - null
     *
     * The NOT operator "!" in front of empty() will flip the value returned by empty(). So if empty() returns true, the
     * NOT operator will flip it to false. This important because we only what the code within the "if" statement to
     * execute if $_POST['partialSearch'] is NOT empty.
     */
    if(!empty($_POST['partialSearch'])) {
        /** Store the results of get_users_by_username(), so we can count the number of results without re-running the function. */
        $users = get_users_by_username($_POST['partialSearch']);
    
        /**
         * Foreach loops with through warnings if user_profile() returns an empty value. Make sure count($users) is > 0
         * before running the loop.
         */
        if(count($users) > 0) {
            foreach($users as $user) {
                print '<p>
                      <a href="ViewProfile.php?uid=' . $user['memberID'] . '">
                          ' . $user['username'] . '
                      </a>
                   </p>';
            }
        } else {
            print "<p>No Results</p>";
        }
    }
    
    /**
     * In files with only PHP code, you do not need the closing PHP tag.
     *
     * "?>"
     */
    

    用户个人资料

    <?php
    /**
     * Fetch user from database by their memberID.
     *
     * @param $id - The user's ID
     *
     * @return array - The user database record.
     */
    function get_single_user_by_id($id)
    {
        $servername = "localhost";
        $username   = "root";
        $password   = "root";
        $dbname     = "coursework_db";
    
        // Create connection
        $conn = new mysqli($servername, $username, $password, $dbname);
        // Check connection
        if($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
    
        $sql    = 'SELECT memberID, username FROM members WHERE memberID = ' . $id;
        $result = $conn->query($sql);
    
        //Return single user
        return $result->fetch_assoc();
    }
    ?>
    
    <!DOCTYPE html>
    <html>
    <head>
        <title>Search Demo</title>
    </head>
    <body>
    
    <?php
        if(!empty($_GET['uid'])) {
            $user = get_single_user_by_id($_GET['uid']);
    
            if(!empty($user)) {
                print "<h1>Welcome " . $user['username'] . "!";
            } else {
                print "User with ID " . $_GET['uid'] . " doesn't exist.";
            }
        } else {
            //No UID was provided
            print "Please provide a UID to a valid user.";
        }
    ?>
    
    </body>
    </html>
    

    提示 1 不要在应用程序中使用mysqlmysqli 数据库连接。这两个连接都已被弃用,并且非常不安全。查看thisthis 了解SQL 注入攻击。为防止此类攻击,请使用PHP Data Objects (PDO)

    提示 2 在另一个文件中定义您的函数,与您的 HTML 分开。将函数定义放在 HTML 旁边很快变得混乱。您可以使用 PHP 的 includerequire 函数来执行此操作。 (learn about it here)

    提示 3 使用重复代码通常是不好的做法。您正在使用相同的代码在两个页面(搜索 ajax 和配置文件页面)上连接到您的数据库。我建议构建一个数据库类来处理应用程序的所有数据库事务,这样您就没有重复的代码。 This will help you with that.

    更新

    您的搜索栏 PHP 代码存在几个问题:

    第一

    您的代码中的以下行只会获取完全匹配:

    $stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE ? 
                    LIMIT 3");
    

    为了实现您想要的自动完成搜索,您需要为其添加通配符:

    $stmt = $conn->prepare("SELECT username FROM members WHERE username LIKE '?%' LIMIT 3");
    

    “%”还将包括以搜索值开头的用户名。

    第二

    在同一个文件中,$searchResults 变量未定义。您的结果字符串将始终为空。

    您需要更改循环遍历结果并为每个结果打印一个链接。

    while ($stmt->fetch()) {
    
        echo $username;
    
        echo "<div>".$searchResults."</div>";
    }
    

    到:

    $results = $stmt->fetchAll();
    
    if($results > 0) {
        foreach($results as $user) {
            print '<p>
                <a href="ViewProfile.php?uid=' . $user['memberID'] . '">
                    ' . $user['username'] . '
                </a>
            </p>';
        }
    } else {
        print "<p>No Results</p>";
    }
    

    【讨论】:

    • 感谢您的帮助,您的笔记让一切变得清晰易懂。我已经进行了您建议的更改。但是我仍然有同样的问题,我的搜索栏结果不是个人资料页面的链接
    • 我忘了提供一些对该过程至关重要的代码。希望现在更有意义
    • 我提供的代码示例是一个完整的应用程序,可以满足您的要求。检查您的搜索条形码与我提供的示例之间的差异。您将看到链接被附加到结果的位置。
    • 我更新了我的答案,包括您可以进行的更改以获得所需的结果,而无需进行太多更改。
    • 我已进行更改,但收到此错误。在第 19 行的 /home//Spark/searchbar.php 中调用非对象的成员函数 bind_param()。
    猜你喜欢
    • 2020-10-26
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多