<?php

class MSQLGrid extends MDataGrid
{
    public $totalRecords;

    public function __construct($database, $sql, $columns, $href, $pageLength, $index, $name, $useSelecteds = true)
    {
        parent::__construct(NULL, NULL, $href, $pageLength, $index, $name, $useSelecteds);
        $this->db = $this->manager->getDatabase($database);
        $countSQL = clone $sql;
        $countSQL->columns = array('count(*) as CNT');
        $queryCNT = $this->db->getQuery($countSQL);
        $this->totalRecords = $queryCNT->fields('CNT');

        $range = new MRange($this->pageNumber, $this->pageLength, $this->totalRecords);
        $this->sql = $sql;
        $this->sql->setRange($range);
        $this->query = $this->db->getQuery($this->sql);
        $this->setColumns($columns);
    }

    public function generateData()
    {
        global $state;

        $this->data = $this->query->result;

        $this->orderby = $this->page->request('orderby');

        if ($this->ordered = isset($this->orderby))
        {
            $this->query->setOrder($this->orderby);
            $state->set('orderby', $this->orderby, $this->name);
        }

        if ($this->getFiltered())
        {
            $this->applyFilter();
        }

        $this->rowCount = $this->query->getRowCount();

        if ($this->pageLength)
        {
            $this->pn->setGridParameters($this->pageLength, $this->totalRecords, $this->getURL($this->filtered, $this->ordered), $this);
            $this->query->setpageLength($this->pageLength);
        }
        else
        {
            $this->pn = null;
        }
    }

}
?>