You should use SQL to get the data you want, then use your host language to display the data. Those are 2 separate operations, and you'll be better off not mixing them. If you're going to let your users go backward, you're going to have to cache the data anyway.
Regards