I had some trouble descriping this “problem”. Please feel free to change the title to something more descriptive for this subject.
I have a database and want to give users the opportunity to choose how to sort the results, search the database, etc.
I am using PHP and MySQL.
I made this table setup as an example:
table Persons
+----+------+----------+------------+------+-----+
| id | age | gender | date | hits | car |
+----+-----------------+------------+------+-----+
| 1 | 18 | male | xx.xx.xxxx | 1040 | 1 |
| 2 | 35 | female | xx.xx.xxxx | 443 | 2 |
| 3 | 67 | male | xx.xx.xxxx | 453 | 2 |
| 4 | 10 | male | xx.xx.xxxx | 3454 | 4 | ==> 4 means Citroen
| 5 | 98 | female | xx.xx.xxxx | 323 | 6 |
+----+------+----------+------------+------+-----+
table Cars
+----+----------+
| id | model |
+----+----------+
| 1 | Porche |
| 2 | Ferrari |
| 3 | Volvo |
| 4 | Citroen |
| 5 | VW |
+----+----------+
A way to select data from the database could be like this:
$sql = "SELECT *, DATE_FORMAT(date, '%b %e, %Y') AS show_date FROM persons ORDER BY date DESC LIMIT 100";
But, what if i want to give the users the opportunity to sort by date, hits, rating (another table) both descending and ascending and also the opportunity to only select persons below age X with the gender of male (for example). How do i do this? Do i need to make if else for all possible querys or is it possible in one single query?
I dont need a finish code snippet, i just need to know if there are any good articles or a “Best Practice”-way to do this. The easiest and most secure method is prefered.
P.S. what do you call this kind of ‘problem’?
In your search query function, just take the search fields, options, etc. and build up your query string. If the
SELECTstatement will always pull the same fields, then you can start by creating the query up to theWHEREclause, and build from there. (Make sure to protect user input from sql injection attacks. Use prepared statements, or suggestive methods from the manual (defined bygetSqlVal()in my ex. code.)) Here is a small example: