Display unlisted auto-complete search results with PHP

前端 未结 1 1819
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-22 00:50

I am trying to display an unlisted search results which is able to have a click event to a target html page based on the search from the database (mysql).

I am using

1条回答
  •  心在旅途
    2020-12-22 00:55

    Use the on select callback (its in the docs), include the id, label and value in your json then on click use a window.location.href to navigate to the page. You could also load the content in using an ajax call.

    So for example using ajax get the content:

    
    
        
            
            
            
            
            
            
       
       
           
    Home

    Search Database (JSON)



    And your search.php file, would look like the following which is safe from SQL injection as it uses prepared queries:

     'could not connect database']);
    }
    
    // auto complete search term 
    if (isset($_GET['term'])) {
        //get search term
        $searchTerm = isset($_GET['term']) ? '%'.$_GET['term'].'%' : null;
    
        //get matched data from name table
        $stmt = $con->prepare("SELECT * FROM artwork WHERE name LIKE ? ORDER BY name ASC");
        $stmt->bind_param('s', $searchTerm);
    
        $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    
        foreach ($result as $row) {
            $data[] = [
                'id' => $row['id'],    
                'label' => $row['name'],    
                'value' => $row['id'],    
            ];
        }
        $response($data);
    }
    
    // result item
    if (!empty($_GET['id'])) {
        //get matched data from name table
        $stmt = $con->prepare("SELECT * FROM artwork WHERE id = ? LIMIT 1");
        $stmt->bind_param('i', $searchTerm);
        $response($stmt->get_result()->fetch(MYSQLI_ASSOC));
    }
    ?>
    

    Untested but should work.

    0 讨论(0)
提交回复
热议问题