Skip to content

Instantly share code, notes, and snippets.

@sakydev
Last active September 3, 2021 09:30
Show Gist options
  • Save sakydev/f8013bd0b54c93978cbd39253d5e8172 to your computer and use it in GitHub Desktop.
Save sakydev/f8013bd0b54c93978cbd39253d5e8172 to your computer and use it in GitHub Desktop.
php+mysql: dynamic PHP function to select anything from a mysql table
<?php
// Please replace TABLE:: actions with your own DB class
// I wrote this class while working with a Laravel based project
// Function is also being used in a project of mine called BriskLimbs
public function list($parameters = array()) {
$fields = array('*');
$limit = $this->limit;
if (!empty($parameters['limit'])) {
$limit = explode(',', $parameters['limit']);
}
$sort = isset($parameters['sort']) ? explode('|', $parameters['sort']) : 'id';
$query = Table::skip($limit['0'])->take($limit['1']);
if ($sort) {
if (is_array($sort)) {
$query->orderBy($sort['0'], isset($sort['1']) ? $sort['1'] : 'DESC');
} else {
$query->orderBy($sort);
}
}
foreach ($parameters as $column => $condition) {
if ($column == 'fields') {
$fields = explode(',', $condition);
if (!$this->validateKeys($fields)) {
return error($this->error);
}
continue; // values are used at end when calling get()
}
if ($this->validateKey($column)) {
if (is_array($condition)) {
if (isset($condition['2'])) { // support for between, in etc
$query = $query->where($column, array($condition['0'], $condition['1']), $condition['2']);
} else {
$query = $query->where($column, $condition['0'], $condition['1']);
}
} else {
$query = $query->where($column, $condition);
}
}
}
if (isset($parameters['keyword'])) {
$keyword = $parameters['keyword'];
$query->where('title', 'like', '%' . $keyword . '%');
$query->orWhere('tags', 'like', '%' . $keyword . '%');
$query->orWhere('description', 'like', '%' . $keyword . '%');
}
if (isset($parameters['count'])) {
return $query->count();
}
return $query->get($fields);
}
// Usage examples below
// list items by specific uploader
$parameters['uploader_name'] = 'uploader_name';
$table->list($parameters);
// list videos longer than 60 seconds
$parameters['duration'] = array('60', '>');
$table->list($parameters);
// most recent items by limit
$params['limit'] = 10;
$response = $table->list($params);
// most viewed items
$params = array('sort' => 'views');
$response = $table->list($params);
// get videos longer than 60 seconds by jon_snow with more than 100 views
$params = array(
'uploader_name' => 'jon_snow',
'duration' => array('60', '<')
'views' => array('200', '>')
);
$response = $table->list($params);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment