Skip to content

Instantly share code, notes, and snippets.

@gskema
Last active August 5, 2016 12:39
Show Gist options
  • Save gskema/347c1c420c751d80187b90559d394a93 to your computer and use it in GitHub Desktop.
Save gskema/347c1c420c751d80187b90559d394a93 to your computer and use it in GitHub Desktop.
[SQL, PHP]: Fetch rows from two column ordered lists by specifying IDs
<?php
/**
* Returns customer notifications
*
* @param int|null $limit
* @param int|null $afterId
* @param int|null $beforeId
*
* [0]*************************************[totalRows]
* [0]*****[$beforeId]---------------------[totalRows]
* [0]-----[$afterId]**********************[totalRows]
* [0]-----[$afterId]******[$beforeId]-----[totalRows]
*
* $limit can be applied to all cases.
* For example, 10 stars (rows) starting from the left will be returned.
*
* @return array
*/
public function getNotifications($limit = null, $afterId = null, $beforeId = null)
{
$sql = new DbQuery();
$sql->select('id_notification, icon, title, url, message, seen, date_add')
->from('notification')
->where('id_customer = '.(int)$this->id_customer)
->orderBy('date_add DESC')
->orderBy('id_notification DESC');
if (null !== $limit) {
$sql->limit((int)$limit);
}
if (null !== $afterId) {
$a = $this->getNotification($afterId, array('date_add'));
$sql->where(
' (date_add = \''.pSQL($a['date_add']).'\' AND id_notification < '.(int)$afterId.')'
.' OR (date_add < \''.pSQL($a['date_add']).'\')'
);
}
if (null !== $beforeId) {
$b = $this->getNotification($beforeId, array('date_add'));
$sql->where(
' (date_add = \''.pSQL($b['date_add']).'\' AND id_notification > '.(int)$beforeId.')'
.' OR (date_add > \''.pSQL($b['date_add']).'\')'
);
/**
* Nonsensical query?
* [0]-----[beforeId]-----[afterId]-----[totalRows]
*/
if (!empty($a) && strtotime($b['date_add']) > strtotime($a['date_add'])) {
return array();
}
}
return (array)$this->db->executeS($sql);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment