Navigate Throught MySQL Result - php

I have searched everywhere but could not get anything. The scenario is that when I run a select statement from MySQL/PHP, I want to use Next & Previous buttons to navigate backwards and forward through the results.
Does anyone know how I can accomplish this?
Here's how I run the query: select everything from members where hair = black;
This returns 8 results, and I have a page like so details.php?id=3 which takes id and display the details.
I want to be able to keep clicking the next button and move to another id from the result.
How do I accomplish this?
Thank you for your assistance.

If you mean to display 1 product details per page with Next buttons, then
1) Get the total rows from table
2) Find total number of pages like
$totalPages = $totalRows; //since 1 record per page
3) Loop thru $totalPages value to generate next links
4) Get the id of product from page url $_GET
5) Query sql using te product id obtained frm GET
Well thats the basics, hope your get it

Assuming you have all ids in the $allIds var, try something like this:
<?php
$id = (int) $_GET['id'];
$key = array_search($id, $allIds);
$nextId = $allIds[$key+1];
?>

Well, you have 2 different scopes here to address, first, when you query you are in PHP/Server side mode. PHP gets some data, processes it, shows some of it to the knowledge i have of your problem and then sends it to the browser.
Next, you have the client scope, where the client has the HTML rendered to his screen and has the possibility to click NEXT and PREVIOUS. When he does that, he issues a request to the server to get the NEXT or PREVIOUS record based on the current one.
You have 2 scenarios to work this problem out:
1) Load the whole data into memory and scan it to find your current position, see if there is a NEXT and PREVIOUS element and respond to the request of the user. If the user asked for the NEXT, easy, just move one more record. If the user asked for PREVIOUS item, then when scanning using a WHILE or FOR/FOREACH, always keep in memory the "lastitem" you saw, you can use this "lastitem" as your PREVIOUS item.
2) In the event you have many (i mean like more than 1000) items, you need to use a little subquery magic and work this out using SQL.
select everything from members where hair = black AND id = XYZ ORDER BY id LIMIT 2;
This will return you the CURRENT AND NEXT elements. Then call the same query again but this time, order it DESC so that your 2 items are the CURRENT AND PREVIOUS.
select everything from members where hair = black AND id = XYZ ORDER BY id DESC LIMIT 2;
Note that you can order this the way you want, the goal is to get a static result, something that always gets out the same way so that you can reverse it and get the items around the selected one.
I hope this helps you

Related

Reorder pictures in a webgallery

I have a webgallery (made with laravel) and would like to add the possibility to reorder the images... Now, I have thought of several approaches but for every aproach i find that there should be a better way of doing it.
the gallery does not use javascript, so ones changes have been made it needs to be sumbitted and reloaded to reflect the changes
The main difficulties are:
how to store the order in the database? an additional Integer column?
how to add a picture "between" two others?
how to handle it at a frontend level?
So far the best ideas I had are these:
a column with integers, order by clause on this column. Frontend: a move up and a move down button.
problems of this solution: it needs a refresh after each single movement. it needs to identify the previous/next picture and swap the number with that one. To move a single pic from the end of the gallery to the top it takes forever.
a column with integers, automatically prefilled in steps of 100, order by this column + upload time in case of same numbers, Frontend: a textbox where the user can specify the integers for each picture and a submit button.
problems of this solution: does not look very professional. solves all the problems of the previous solution
same as previous solution but with double values to be able to insert pictures without limits.
They all dont seem the real deal.. Any sugestion on how to do it properly is welcome. thanks
I have done that kind of sorting in OpenCart products list (custom backend design)
Sort order was additional column order INT(11) in database
We had 3 input fields: up/down/custom
Where custom was dropdown of all indexes from 1 to max-items.
All inputs does the same:
Take new order value and shift all elements except itself. Up or down shift depends if you move element to front or to back of current position
UPDATE order FROM products SET order = :newOrder WHERE id = :currentItemId
if ($newOrder > $oldOrder)
UPDATE order FROM products SET order + 1 WHERE order >= :newOrder AND id != :currentItemId
else
UPDATE order FROM products SET order - 1 WHERE order <= :newOrder AND id != :currentItemId
Inserting does the same update, just first query becomes INSERT INTO
To get rid of ugly refresh of page on every action we do Ajax requests and re-sorted DOM with jQuery

PHP/SQL - how to generate pages based on database rows

I am new to php, mostly learning from examples, and having a little bit of trouble.
I already searched for this, but couldnt find exactly what i was searching for, or at least couldnt understand it.
I am trying to create somekind of a "news" system. I have a database with 3 columns:
tid - auto-incremented, the id # for the news i post
created_by - who created it...obviously
text - the news themselves
So, is there a way that every time i post some new article it gets a new unique page, based on its id?
In example - mysite.com/news.php?id=3 will show the article with "tid"=3 (from the sql table).
Lets say news.php is my main file and i want its content to change everytime when the ?id in the url changes.
Thanks and wish you a successful week ahead.
<?php
$currentID = $_GET['current_id']; // get current id out of the link
// add some logic to validate it is a valid id to prevent sql injection
build the query which is get next post that is above
current id and limit it to 1 post only
"SELECT * FROM news where id > $currentID limit 1";
back link would turn the greater than to a less than. you would need to have checks to ensure you cant go below 0 and cant go max id number. A quick count of records would do it. or catch not found records to go back to the start

How can one display different records on different pages?

For eg I have 5 records of same user. What is the best way I can sort and display each one of them on a different page using next and previous links.For eg on clicking previous i must get previous record. Then i again click previous i must get previous to that record and so on.
Pick an order and set it with ORDER BY [order], then use LIMIT start, amount to slice the result.

Pagination with ajax

I've build an application (with PHP, Codeigniter and jQuery) that uses ajax for pagination, similar to how Twitter made it back in the day (clicking a button to load in more data).
It's all quite well, but there are a few issues however.
When there are no more posts left to load in, I want the "load-more"-button to be removed. However, right now I can only check if there are any posts left when I click the button, and the script returns null.
This is how it is now: Let's say that there are 14 posts in the database. 5 is loaded per default.
1 - click load-more, 5 more posts are loaded. 4 remain.
2 - click load-more, the remaining 4 posts are loaded.
3 - click load-more, no more remaining posts, button disappears
But I want to get rid of step 3, the application should "be aware" of that there are no more posts left to render at step 2.
I am sure there are a simple way that I haven't thought if yet...
simple. select 6 posts instead of 5 and display only 5.If no of posts less than 6 dont display more button.
if ($num_rows < 6){
//remove more button
}
You could set a global Javascript variable holding the amount of total posts something like this:
var total = <?php echo $total ?>;
And after the call compare the amount to the total:
if($('.post').length == total) // .post being database results
$('#loadmore').hide();
Return a JSON object with one property that is an array (the entries) and one property that is a bool "EOF" or such to indicate when there is no more entries to load.
if(response.EOF)
//Hide button..
Ohh and add the id of the last post from current pagination in the AjaxRequest.
That way the server gives you say 25 posts from the last one it gave you.
Then you dont get offsets if a new post is added during pagination.
you could try something like this
if ($num_rows < 5){
/*what ever you want removed */
}
at the end of you loop
Please, please, please - do not do pagination in Ajax!
It is pain in the a$$ to navigate such pages natural way, unable to use back button or reload button or set a bokmark or anything!
not to mention clients that doesn't support js at all

PHP/SQL Cycle items every x minutes

I have a friend who runs an online auction website. He currently has a featured items section on the homepage that he wants to have cycle an item every X amount of minute. The site runs off a MySQL database which I haven't actually seen yet.
The current code that he is using is a big, long messy Javascript code that is causing all kinds of errors.
The items would have to cycle in order and when they get to the end, go back and repeat again.
What would be the best approach to take to this using PHP?
EDIT: I mean from a backend SQL perspective. Not the UI.
Thanks
Ben
Assuming you have a separate table for the featured items (probably has an item ID referencing the main items table and maybe other info)... In this table, add a last_featured column to represent the time the item was last shown. From there, you can manipulate your queries to get a rotating list of featured items.
It might look something like this (as a weird pseudocode mix between PHP & MYSQL):
// select the most recent item in the list, considered the current item
$item = SELECT * FROM featured_items ORDER BY last_featured DESC LIMIT 1;
if ($item['last_featured'] > X_minutes_ago) {
// select the oldest item in the list, based on when it was last featured
$item = SELECT * FROM featured_items ORDER BY last_featured ASC LIMIT 1;
// update the selected item so it shows as the current item next request
UPDATE featured_items SET last_featured=NOW() WHERE item_id = $item['item_id'];
}
Note that this requires 3 call to the database... There may be a more efficient way to accomplish this.

Categories