Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL order by error in PHP

Tags:

php

mysql

I'm making a simple cms system for a site I'm making for non-tech users to edit...

So far so good but when I try and run this code I keep getting: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''pages' ORDER BY 'pages'.'pageOrder' ASC LIMIT 0 , 30' at line 1

By the error it looks like a problem with the order by section and indeed it works without it...

$sql = "SELECT * FROM 'pages' ORDER BY 'pages'.'pageOrder' ASC LIMIT 0 , 30";

$result = mysql_query($sql) or die(mysql_error());

Now I know there is nothing wrong with the code because originally I wrote my own SQL but then after it failed I robbed some from phpmyadmin and it still gives the error but it works in phpmyadmin...

I'm really at my wits end with this, help is very much appreciated thank you...

like image 377
theflyinghaiwian Avatar asked May 10 '26 05:05

theflyinghaiwian


2 Answers

You shouldn't write 'pages'. Use backticks instead of single quotes for table and column names. Single quotes are used only for strings.

And backticks aren't necessary here anyway. Backticks are generally only required for names that are reserved words in SQL, and names containing special characters or spaces. So you could just do this:

SELECT * FROM pages ORDER BY pageOrder LIMIT 30
like image 136
Mark Byers Avatar answered May 12 '26 20:05

Mark Byers


The quotes in your query are incorrect. You could either use

$sql = "SELECT * FROM `pages` ORDER BY `pages`.`pageOrder`  ASC LIMIT 0 , 30";

if you really need to fully qualify the table/column, or just leave that out and use

$sql = "SELECT * FROM pages ORDER BY pageOrder ASC LIMIT 0 , 30";
like image 22
hangy Avatar answered May 12 '26 20:05

hangy