Last active
December 28, 2015 05:29
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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