-1

I am trying to limit the amount of search results on each page like Google does. I am also using a SQL database to organize my keywords and everything. Here is my code

<?php
$q = $_GET['q'];
$terms = explode(" ", $q);

//connect
mysql_connect("localhost", "root", "") or die ("Could Not Connect");
mysql_select_db("search") or die ("Could Not Connect To database");

$query = "SELECT * FROM search ";

$i=1;
foreach ($terms as $each){
    if ($i == 1) {
        $query .= "WHERE ";
        $query .= "keywords LIKE '" . mysql_real_escape_string("%" . $each . "%") . "' ";
    } else {
        $query .= "OR keywords LIKE '" . mysql_real_escape_string("%" . $each . "%") . "' ";
    }
    $i++;
}

$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0)
{      
    while($row = mysql_fetch_assoc($query))
    {
        $id = $row['id'];
        $title = $row['title'];
        $description = $row['description'];
        $keywords = $row['keywords'];
        $link = $row['link'];

        echo "<h3><a href='$link'>$title</a></h3><h4>$link</h4>$description<br /><br />";
    }
} else {
    echo "<b>No Results Found</b><br><br>Suggestions:<br>
        Make sure all words are spelled correctly.<br>
        Try different keywords.<br>
        Try more general keywords.";
}
//disconnect
mysql_close();

?>

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

1

After your foreach ($terms as $each){} you need to add an ORDER BY and LIMIT to the query, like so:

$query .= "ORDER BY keywords LIMIT 0, 10";

That will give you the first 10 results. Alter the LIMIT vars as needed. The first number is the offset (zero based, aka first result is 0, sixth result is 5) and the second number is the number of rows to return.

The ORDER BY helps with consistent results. You don't need it, but sometimes results can be weird.

See this question for more info if you need it.

Community
  • 1
  • 1
TunaMaxx
  • 1,782
  • 12
  • 18
  • that works great but what if i wanted to add them to a second page instead of just cutting off the results – Joshua Howard Aug 24 '14 at 18:53
  • It depends. Are you making a new query for page two of the results, or do you want to worked from the initial cached query? – TunaMaxx Aug 24 '14 at 18:55
  • OK, then just change the `$query` to be something like `$query .= "ORDER BY keywords LIMIT 10, 10";` and that will now return the 11th through 20th results. Make the offset a variable like `$query .= "ORDER BY keywords LIMIT " . (int) mysql_real_escape_string($_GET['offset']) . ", 10";` and you can change it per page in the query string. However, as others have said, you should be working with at least mysqli instead of the outdated mysql functions. – TunaMaxx Aug 24 '14 at 18:59