简体   繁体   中英

mysql within Joomla next and previous SQL statement within orderby

I know things are escaped incorrectly, but I am trying to write a previous/next query to get the next id and previous id within an order, but my output does not match the phpmyadmin sorting, which it should. I just have the 'next' written, and would write the previous with reverse conditions. This query seems to give me the next highest ID value number within the order...I need the next or previous in the order index...can anyone help?

$db = JFactory::getDBO();
$query = "SELECT image_id FROM #__jxgallery_images WHERE image_id >".$currentid."' ORDER   BY '".$ordering." ".$direction." LIMIT 1";
// Executes the current SQL query string.
    $db->setQuery($query);
// returns the array of database objects
    $list = $db->loadObjectList();
// create the list of ids
    foreach ($list as $item) {
    $next = $item->image_id;
    echo $next.'<br/>';
    }
echo 'The next ID in this sort state is&nbsp;'.$next.'<br />';
?>

This is phpmyadmin and it is right...

SELECT * FROM `jos_jxgallery_images` 
ORDER BY `jos_jxgallery_images`.`hits` DESC 
LIMIT 0 , 30

I have now matched this query in my code to get the same results. My variables fill in the ($ordering) 'hits' field and the 'desc' ($direction) within my clause. That works fine. The image_ids and hits aren't special...just numbers. When hits are ordered, the image_ids are resored to match. I don't need the next value of image_id as to what is in the field. I need the next row or previous row, regardless of value, based on the current image_id I plugin.

These are actual image_ids LIMIT 5, and these are Ordered by the hits field Descending:

52791 
52801 
52781 
52771 
52581`

Now if the current image I'm looking at has an id of 52791 , then previous should be nothing and next should be 52801 . What my query is doing I think is giving me an image_id of a higher valued number as 'next' because that is the next highest VALUED image_id, not the next row. I can see why in the query, I am asking for greater than...but I just need the next row

I think the problem is with your WHERE condition: WHERE image_id >".$currentid."'

If I understand what you're trying to do, one way to do it is this:

$query = "SELECT image_id FROM `#__jxgallery_images` ORDER BY ".$ordering." ".$direction." LIMIT 2";

$db->setQuery($query);

$list = $db->loadObjectList();

$next_item = $list[1]->image_id;

Notice that the WHERE condition is removed from the query, and I also changed LIMIT 1 to LIMIT 2 . This way, the query basically returns your top value and the one with the next highest "hits" value.

I hope this helps.

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