Create dynamic sites with PHP & MySQL - Searching our data
(Page 15 of 16 )
Information is useless if you can't find the data you require from a wealth of information. We need a way to search our database, so let's implement a search function. The page will show a static form initially and will show the search result when we have something submitted.
The script checks whether a search string exists. If $searchstring contains a value, then we have something to search; otherwise, we just show an HTML form. The part of code that searches is similar to our viewdb2.php. The SQL command deserves a bit of explanation here. Let's look at it closely. The SQL command is:
"SELECT * FROM personnel WHERE $searchtype LIKE '%$searchstring%' ORDER BY firstname ASC"
Two news things are introduced here, "LIKE" and "ORDER BY". LIKE simply means 'sounds like'. The '%' sign represents any possible combination of characters (numbers or letters). So to find people whose first name starts with 'J' we would use the SQL command:
"SELECT * FROM personnel WHERE firstname LIKE 'J%'"
To find those people with a name ending with J we have to use '%J'. If we wish find people with 'J' anywhere in their name (first, middle, or last) we have to use '%J%'.'ORDER BY' simply orders the records in ascending or descending order. The syntax is: "ORDER BY fieldname order_ method" where order_ method is ASC or DESC allowing the ordering to be done in ASCending or DESCending order.