BlackCoder
BlackCoder

Reputation: 115

Order by and LIMIT both not working together in MySQL Query

i'm trying to Order by Desending and want to limit 30 in Query

PHP CODE

$page = $_POST['page'];
$cur_page = $page;
$page -= 1;
$per_page = 30;
$previous_btn = true;
$next_btn = true;
$first_btn = true;
$last_btn = true;
$start = $page * $per_page;

$query_pag_data = "SELECT * from titles LIMIT $start, $per_page ORDER BY id DESC";

ERROR : MySql ErrorYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ORDER BY id DESC' at line 1

PS: i'm using pagination... so limiting 30 result like this

Upvotes: 0

Views: 1786

Answers (5)

Pupil
Pupil

Reputation: 23948

LIMIT statement should always come at the end of the query.

Upvotes: 0

Abhinav
Abhinav

Reputation: 115

You need to put ORDER BY statement first before LIMIT

Correct syntax is as follows:

SELECT * FROM *table_name* WHERE *condition* ORBER BY *field_name* LIMIT *limit*;

Upvotes: 0

Tucker
Tucker

Reputation: 7362

You have to put the limit at the end of the query for proper syntax:

$query_pag_data = "SELECT * from titles ORDER BY id DESC  LIMIT $start, $per_page";

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

change positions or LIMIT and ORDER BY, like:

$query_pag_data = "SELECT * from titles ORDER BY id DESC LIMIT $start, $per_page";

Upvotes: 1

Jason OOO
Jason OOO

Reputation: 3552

correct syntax is:

SELECT * from titles 
ORDER BY id DESC
LIMIT $start, $per_page 

LIMIT at the end of the query.

Upvotes: 3

Related Questions