简体   繁体   中英

MySQL Syntax Issue - ORDER BY - Joomla PHP

I have a syntax issue that I can't seem to figure out. I'm following the Joomla docs found here:

https://docs.joomla.org/Selecting_data_using_JDatabase#Selecting_Records_from_a_Single_Table

And I'm getting this error:

1064 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 'order DESC' at line 3 SQL=SELECT `id`,`image`,`order`,`status` FROM `vsem6_session_1` ORDER BY order DESC 

My Query is:

$db = JFactory::getDbo();
$query = $db->getQuery(true);

$query->select($db->quoteName(array('id', 'image', 'order', 'status')));
$query->from($db->quoteName('#__session_' . $id));
$query->order('order DESC');

$db->setQuery($query);
$results = $db->loadObjectList();   

return $results;

It works great if I take out the order clause, but of course the results aren't ordered. I've search high and low and can't figure it out. Anyone notice anything? I am 100% certain there is an "order" column in the table.

I tried this, which shows no error, but it still doesn't order properly.

$query->orderby('order DESC');

order is a reserved word as its used in order by . So to solve mysql's confusion you need to mark your use of order as a field name with back ticks

$query->order('order DESC');

The problem with this is that that you have not used quoteName().

$query->order($db->quoteName('order') . 'DESC');

Even though you said you would change the field name, I'm adding this for the situation in which someone could not change the name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM