catfan / Medoo

The lightweight PHP database framework to accelerate the development.
https://medoo.in
MIT License
4.84k stars 1.15k forks source link

How to use LIMIT OFFSET? #120

Closed KaitaniLabs closed 7 years ago

KaitaniLabs commented 10 years ago

I'm confused about how to include LIMIT & OFFSET in a select query.

KaitaniLabs commented 10 years ago

Nevermind I worked it out. Would be useful in the documentation, as officially LIMIT is not part of the WHERE clause. (Can have LIMIT without WHERE)

numediaweb commented 9 years ago

It is not documented by looking at the code:

if (isset($where['LIMIT']))
            {
                $LIMIT = $where['LIMIT'];

                if (is_numeric($LIMIT))
                {
                    $where_clause .= ' LIMIT ' . $LIMIT;
                }

                if (
                    is_array($LIMIT) &&
                    is_numeric($LIMIT[0]) &&
                    is_numeric($LIMIT[1])
                )
                {
                    if ($this->database_type === 'pgsql')
                    {
                        $where_clause .= ' OFFSET ' . $LIMIT[0] . ' LIMIT ' . $LIMIT[1];
                    }
                    else
                    {
                        $where_clause .= ' LIMIT ' . $LIMIT[0] . ',' . $LIMIT[1];
                    }
                }
            }
hirdeshvishwdewa commented 8 years ago

We can use OFFSET same as like we do LIMIT by making the following few changes-

  1. At line 425 by adding OFFSET for $single_condition
  2. Replace the code which is setting LIMIT to the what shown below-
if (isset($where[ 'LIMIT' ]))
            {
                $LIMIT = $where[ 'LIMIT' ];
                if (is_numeric($LIMIT))
                {
                    if(isset($where[ 'OFFSET'])){
                        $OFFSET = $where[ 'OFFSET'];
                        if (is_numeric($OFFSET))
                        {
                            if ($this->database_type === 'pgsql'){
                                $where_clause .= ' OFFSET ' . $LIMIT . ' LIMIT ' . $OFFSET  ;
                            }
                            else{
                                $where_clause .= ' LIMIT ' . $OFFSET . ', ' . $LIMIT;
                            }
                        }
                    }else{
                        $where_clause .= ' LIMIT ' . $LIMIT;
                    }
                }
            }

Thats it!

catfan commented 7 years ago

Medoo 1.4 is improved with that.