I want to only display 5 results from my database with my PHP search script. How can I do this?
My PHP code is:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
if(!empty($_GET['q'])){
$query= mysql_real_escape_string(trim($_GET['q']));
}
$searchSQL = "SELECT * FROM links WHERE `title` LIKE '%{$query}%'";
$searchResult = mysql_query($searchSQL);
while ($row=mysql_fetch_assoc($searchResult)){
$results[] = "<div class='webresult'><div class='title'><a href='{$row['url']}'>{$row['title']}</a></div><div class='desc'>{$row['description']}</div><div class='url'>{$row['url']}</div></div>";
}
echo implode($results);
?>
Solution: Add a
LIMITclause to your query, in order to limit the number of the returned results.Suggestion: Place your database querying code inside the if clause, because this way you will avoid troubles of the
GLOBALvariables kind.