(This is actually a repost since I made an mistake before. Whoops.)
The last three days were about considering and mastering the search feature for Starfleet’s Path to 2265. I write this blog post whilst I ponder ways to made the search feature more powerful and intuitive.
As it currently stands, it is a basic search function. When a viewer submits a search query, and SQL query is searches a database and returns an array of results. An if statement checks to see if there are any results. If there aren’t results present, a ‘no results’ message is echoed. If there are results present, the code proceeds to a while loop that iterates until there are no more results to echo out.
In pseudocode, the operation needed to make a search currently looks like this:
- Connect to MySQL Server
- Select MySQL database
- Create variable for the query string received from the search request
- Create variable for the SQL SELECT query that searches for matches within two fields of a database table.
- Create variable to store the raw results from the running the SELECT query, and handle possible MySQL errors
- If number of raw results is more than zero:
- While able to print out raw results:
- Echo a tile containing the data for the result (includes a hyperlink, page name, category, description, and an optional image)
- Echo a tile containing a ‘no results’ message
FYI, a “tile” is the CSS class name I use for the layout element that contains a result or message.
Following that procedure, you can generate results like this…
…from a search box like that:
I have clearly broken the statement I made on my last post about this project saying that I will not be doing any more serious non-styling code! But a search feature is something I should have had from the get-go. There are refinements that ideally need to be made before the website goes onto the internetz; a more advanced search algorithm that can intelligently display relevant results instead of echoing the results in the order they are stored in the database, a more space-efficient results page with filters, and compliant code for when I switch to PHP7 which also requires I use mysqli_* functions instead of just mysql_* or PHP Data Objects (PDO).
Now. Before I end this blog post, below is an example of an implementation of that pseudocode that should work with little modification. Starfleet’s Path to 2265 uses code that is very similar currently. It might be basic, but it works for now. I am more focused on other parts of the website. So if I run behind schedule, I at least have this to fall back on.
Example PHP code:
Example HTML code of a search box that works out of the box with that PHP code: