Skip to content

Instantly share code, notes, and snippets.

@RetiredQQ
Last active January 21, 2024 18:23
Show Gist options
  • Save RetiredQQ/8fe8a93c02775d48f5883735b38b1270 to your computer and use it in GitHub Desktop.
Save RetiredQQ/8fe8a93c02775d48f5883735b38b1270 to your computer and use it in GitHub Desktop.
Datatables with medoo
<?php
require_once 'vendor/autoload.php';
use Medoo\Medoo;
$db = new Medoo([
'type' => 'mysql',
'host' => $dbhost,
'database' => $dbname,
'username' => $dbuser,
'password' => $dbpass,
'charset' => 'utf8'
]);
$where = ['ORDER' => ['full_name' => 'ASC']];
$cols = $db->select('users', '*', ['LIMIT' => 1])[0];
if ($_REQUEST['search']['value'] !== "")
{
foreach ($cols as $key => $value) {
$where['OR'][$key . '[~]'] = $_REQUEST['search']['value'];
}
}
if ($_REQUEST['length'] !== -1) {
$where['LIMIT'] = [$_REQUEST['start'], $_REQUEST['length']];
}
if (isset($_REQUEST['order'])) {
$colIdx = $_REQUEST['order']['0']['column'];
$where['ORDER'] = [$_REQUEST['columns'][$colIdx]['data'] => strtoupper($_REQUEST['order']['0']['dir'])];
}
$users = $db->select('users', '*', $where);
$recordsTotal = $db->count('users', $where);
// A dirty ways
// To prevent empty result on next page when using search box.
unset($where['ORDER']);
unset($where['LIMIT']);
$recordsFiltered = $db->count('users', $where);
$result = [
'draw' => intval($_REQUEST['draw']),
'recordsTotal' => $recordsTotal,
'recordsFiltered => $recordsFiltered,
'data' => $users
];
return json_encode($result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment