2

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'?

3 Answers 3

4

In your search query function, just take the search fields, options, etc. and build up your query string. If the SELECT statement will always pull the same fields, then you can start by creating the query up to the WHERE clause, and build from there. (Make sure to protect user input from sql injection attacks. Use prepared statements, or suggestive methods from the manual (defined by getSqlVal() in my ex. code.)) Here is a small example:

$sql = "SELECT ... FROM Persons p, Cars c WHERE p.car = c.id";

if(isset($_POST["age"]))
    $sql .= " AND age < " . getSqlVal($_POST["age"], 'int');
if(isset($_POST["gender"]))
    $sql .= " AND gender = '" . getSqlVal($_POST["gender"], 'text') . "'";
if(isset($_POST["sortBy"])){
    $sql .= " ORDER BY " . getSqlVal($_POST["sortBy"], 'text');
    if(isset($_POST["sortDirection"]) && $_POST["sortDirection"] == "DESC")
        $sql .= " DESC";
}
3

Simply, you come up with a model that represents their actual request, then you, likely, manifest that model in to a dynamically created SQL statement that returns the appropriate data for their query.

For example, if they just wanted age, gender, sorted by hits, you would know to not bother joining to the Cars table (since they didn't require anything from that table). Whereas if they did want the car model, you would add in the join as appropriate.

2

You could enclose all these options in a switch statement and pass URLs $_GET variables to it.

For example, to customize sorting, pass sort_by variable to the URL:

/my_list.php?sort_by=hits

and construct the swith statement like this:

$sort_by = '';
switch ($_GET['sort_by']) {
    case 'rating':
        $sort_by = ' ORDER BY `rating` ';
        break;
    case 'hits':
        $sort_by = ' ORDER BY `hits` ';
        break;
    default:
        $sort_by = ' ORDER BY `date` ';
        break;
}

Then your query would look like:

$sql = "SELECT *, DATE_FORMAT(date, '%b %e, %Y') AS show_date
        FROM persons "
        . $sort_by .
        "DESC LIMIT 100";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.