Re: PHP & MySQL Search Results

From: Date: Sat, 14 Apr 2001 17:17:41 +0000
Subject: Re: PHP & MySQL Search Results
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-48559@lists.php.net to get a copy of this message
Hi Jason, Say you have a search form that says search for "searchbox" and the search box has a variable name of "search": <? /* Include connection details, with a variable of $connection */ if (!$page) { $page = 1; } $limit = $page * 25; $limit = $limit - 25; $sql = "SELECT FROM table WHERE searchdata LIKE '$search' ORDER BY searchdata DESC LIMIT $limit,25"; $result = @mysql_query($sql, $connection) or die (mysql_error()); $num = mysql_num_rows($result); if ($num == 0) { ?> NO Valid search results. <? } else { while($row = mysql_fetch_array($result)) { $url = $row['url']; $name = $row['name']; ?> <a href="<? echo "$url"; ?>"><? echo "$name"; ?><BR> <? } if ($page > 1) { echo "<a href=\"search.php?search=".$search."&page=".(page -1)."\">Previous</a>"; } if (($num > 25) && (($limit + 25) < $num)) { echo "<a href=\"search.php?search=".$search."&page=".($page + 1)."\">Next</a>."; } /* End the initial "Else" */ } ?> __________________________________________ Here you will see that if no page is assigend as a variable, it is force assigned to 1. The limit is the number of results the search is limited to. If you do some mathematics (ouch) you will see that the limit works like this: if the page is equal to 1: limit is 1 * 25 = 25. limit = 25 - 25 = 0 The limit in the sql query limits 0,25 (first 25 matches). if the page is equal to 2: limit is 2 * 25 = 50 limit is 50 - 25 = 25 The limit in the sql query limits 25,25 (25 matches After the first 25 matches). if the page is equal to 3: limit is 3 * 25 = 75 limit = 75 - 50 The limit in the sql query is 50,25 (next 25 matches after the first 50). Now, towards the bottom of the code I have supplied, I have next and previous links: if page is greater than 1, you can show a link to a previous page: search.php?search=".$search."&page=".($page - 1) This links back to the search page with the searchg criteria, and the page - 1. if there are more than 25 results ($num) and the (limit + 25) is less than the total number of pages, we can add a next link. If you wanted to add page numbers as links, you could do a while or for loop, but I'd have to use my brain a little more to try and explain that to you. I hope that makes a little sense, I'm not very good at explaining these things. There's a really good tutorial on this at devshed.com James.

« previous php.general (#48559) next »