Search code examples
phplistlimit

Limit fetched data from db into a list in 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...


Solution

  • 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.