douchi5822
douchi5822
2013-06-22 20:24

将获取的数据从db限制为HTML中的列表

已采纳

I'm working on a autosuggest field and it works already. The only thing I'm trying to do now, is to limit the output of data in the list below the search field. Can someone help me how to do it? I tried a few ways already, but ending up with errors. So what I'm trying is to limit the amount of results which get pulled out of the database. I tried doing this in php (I think it's better performance wise, isn't it?). Here's the code that works fine already:

<?php
require_once 'connect.php';

if (isset($_POST['search_term']) == true && empty ($_POST['search_term']) == false) {
    $search_term = mysql_real_escape_string ($_POST['search_term']);
    $query = mysql_query ("SELECT `word` FROM `datalist` WHERE `word` LIKE '$search_term%'");
    while (($row = mysql_fetch_assoc($query)) !==false) {
        echo '<li>', $row['word'], '</li>';
    }   
}
?>

Since I'm not an expert, I would be happy for some help to learn more...

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongping8572 dongping8572 8年前

    The easiest approach would be to update your sql query and add a limit clause. So if you maybe want only the first 10 results, do it like this:

    SELECT `word` 
    FROM `datalist` 
    WHERE `word` 
    LIKE '$search_term%'
    LIMIT 10;
    

    You can do that in php without modifying your query, too, but I found it easiest if you just pull from the database what you need.

    By the way, you're using the old mysql connector. This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.

    点赞 评论 复制链接分享
  • dougou6213 dougou6213 8年前

    You can limit it in your query. It would be better to limit the amount of data you retrieve from the database, rather than retrieve everything and then filter the results later. MySQL is built to run these query's quickly, so use it to your advantage.

    mysql_query ("SELECT `word` FROM `datalist` WHERE `word` LIKE '$search_term%' LIMIT 5");
    

    However you can do it in php if you want by fetching in a for loop:

    $limit = 5 // Make limit whatever you want
    // Make sure you have enough results to fetch
    if(mysql_num_rows($query) < $limit)
       $limit = mysql_num_rows($query);
    
    for($i = 0; $i < $limit; $i++){
       $row = mysql_fetch_assoc($query);
       echo '<li>', $row['word'], '</li>';
    }
    
    点赞 评论 复制链接分享