Skip to content

Instantly share code, notes, and snippets.

@martinbean
Last active December 28, 2015 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinbean/7450357 to your computer and use it in GitHub Desktop.
Save martinbean/7450357 to your computer and use it in GitHub Desktop.
Very crude way of building up raw SQL clauses for filtering and sorting.
<?php
// whitelist columns to filter by
$filterable = array(
'colour',
'size',
'price'
);
// build up string for WHERE clause
$where = array();
// loop over each column and add to WHERE clause
foreach ($filterable as $column) {
if (isset($_GET[$column])) {
if (is_array($_GET[$column])) {
$values = array();
// sanitize each value in array; only accept scalar values (strings, integers etc)
foreach ($_GET[$column] as $value) {
if (is_scalar($value)) {
// TODO: sanitize $value
$values[] = $value;
}
}
$where[] = sprintf('%s IN (%s)', $column, implode(',', $values));
}
else if (is_scalar($_GET[$column])) {
$where[] = sprintf('%s = %s', $column, $this->db->quote($value));
}
}
}
if (count($where) > 0) {
$where = 'WHERE ' . implode(' AND ', $where);
}
else {
$where = ''; // set WHERE clause to empty string if no filters present
}
// whitelist columns to sort by
$sortable = array(
'colour',
'size',
'price'
);
// build up ORDER clause
if (isset($_GET['sort']) && in_array($_GET['sort'], $sortable)) {
$order = sprintf('ORDER BY %s', $_GET['sort']);
if (isset($_GET['direction']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC'))) {
$order.= ' ' . strtoupper($_GET['direction']);
}
}
else {
$order = '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment