开发者

How do I implement search?

I have a semi-functioning s开发者_如何学编程ite. I have a non functional search bar. I want the user to be able to type in a person's name. Then I want the search bar to return the person's name and picture on onkeydown(). Basically like Facebook.

This will need the XHTML/CSS similar to a drop down menu, but with a query to the mysql table. Facebook queries both the first name and last name field which explains why they don't combine the two like twitter does. I only have a full name inserted so that makes that easier. I'll send each letter and match against the full_name mysql column. How do you write the regular expressions to do this or more high level - how do you write the function to do this?

PHP - Pseudo code

function match()
  {
  //  Run Query
  //  Return list(full_name,picture)
  //  If less then 5
         Modify up query to obtain 5
         Embedded if (special case less then 5 available - new site)
           Send
      If more then 5
         Modify down query to obtain 5
      Elseif ==5
         Send

  }

CSS/XHTML/Javascript

function display()
  {
  // Display list - set max returns (5)
  }


Check out the jQueryUI Autocomplete feature, particularly the Remote Datasource and Custom Data and Display examples.

What you'll want on the PHP side is to

  1. Query the database based on supplied search data
  2. Build an array of matching entries
  3. Display that array as JSON data using json_encode()

Update

This is modified from my Facebook friend autocomplete selector.

Here's the core of the JavaScript

jQuery(function($) {
    var field = $('#friend-name'); // text field for name
    var idField = $('#friend-id'); // hidden field for ID
    field.autocomplete({
        minLength: 3,
        width: 240,
        source: 'search.php',
        change: function(event, ui) {
            idField.val(ui.item != null ? ui.item.id : '');
            return true;
        }
    }).data('autocomplete')._renderItem = function(ul, item) {
        var img = '<img src="' + item.picture + '">';
        return $('<li>')
               .data('item.autocomplete', item)
               .append('<a>' + item.label + img + '</a>')
               .appendTo(ul);
    };
});

The PHP part to search based on parameters would look something like this

// search.php

// assuming PDO connection already made in $db
$stmt = $db->prepare('SELECT `id`, `name`, `picture` FROM `Person` WHERE LOWER(`name`) LIKE ?');
$stmt->execute(array(
    strtolower($_GET['term'] . '%')
));
$people = array();
while($person = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $people[] = array(
        'label'   => $person['name'],
        'value'   => $person['name'],
        'picture' => $person['picture'],
        'id'      => $person['id']
    );
}
echo json_encode($people);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜