php fetch database, displaying them customized. - php

During fetching data from database with $result = mysqli_query($con,"select * from MY_table, it display 100 columns at a time. my main aim is to display 10 columns at a time, with the help of next and previous buttons user gonna read remaining. is it possible to do with Javascript , or AJAX, or PHP alone.

The word you're looking for is 'pagination'. You can divide your query results into pages. PHP can fetch a part of the query results, and you can click on a button or link to fetch the next page. That next page can be loaded by an entire page refresh, or by Ajax. In either case, PHP fetches the next results and returns them.
9lessons.info has a tutorial on this exact same topic. Well, more a bunch of snippets than a tutorial, but still..
If you're just starting: forget about Ajax at first. Start with reading about the LIMIT clause in MySQL. It allows you to query a subresult of the query, by limiting the returned rows to a specific range.
You can pass a page (or a range) in the url, so when you click 'Next page', you can just call PHP again with ?page=2 or something in the url. Based on that number, you can query a different range of rows.
The last step is to update only a part of the page using Ajax instead of doing a full page refresh.

You can use limit to your sql query to do this
$start = 0;
$result = mysqli_query($con,"select * from MY_table limit ".$start.", 10");
initially $start will be 0 the change the $start variable as per your prev next ..

Related

Mysqli php ajax Pagination

can someone please explain to me how to approach this issue?
I have a table with 4000 records, a select option and a search field to filter out the table
however I'm trying to figure out the best way to set up pagination.
1st Approach:
Should I make one query against the database and populate the table with all records and then set up the pagination with javascript so I can be able to search for records that are not only shown on the current page?
2nd Approach
Set up the pagination with PHP, make a query via ajax for each page? however I'm afraid that this approach would not allow me to filter out the table if I need to search for a record that is not on the current page.
1st approach: definitely not, loading large number of results for nothing is not recommended.
2nd approach makes more sense. You can use the LIMIT statement inside your SELECT statement to decide which records you want. Ex. if you paginate on 10 elements perpage, you could do
SELECT * FROM Table LIMIT 10
then
SELECT * FROM Table LIMIT 10,10
and so on. Indexes start at 0.
Note that you don't even need Ajax to do that, your next button can specify the offset for the next load of the page. It's a choice based on your knowledge, the size of the rest of the page (minimize load time), ...

How to limit mysql rows to select newest 50 rows

How to limit mysql rows to select newest 50 rows and have a next button such that next 50 rows are selected without knowing the exact number of rows?
I mean there may be an increment in number of rows in table. Well I will explain it clearly: I was developing a web app as my project on document management system using php mysql html. Everything is done set but while retrieving the documents I mean there may be thousands of documents.
All the documents whatever in my info table are retrieving at a time in home page which was not looking good. So I would like to add pages on such that only newest 50 documents are placed in first page next 50 are in second and so on.
But how come I know the exact number of rows every time and I cannot change the code every time a new document added so... numrows may not be useful I think...
Help me out please...
What you are looking for is called pagination, and the easiest way to implement a simple pagination is using LIMIT x , y in your SQL queries.
You don't really need the total ammount of rows you have, you just need two numbers:
The ammount of elemments you have already queried, so you know where you have to continue the next query.
The ammount of elements you want to list each query (for example 50, as you suggested).
Let's say you want to query the first 50 elements, you should insert at the end of your query LIMIT 0,50, after that you'll need to store somewhere the fact that you have already queried 50 elements, so the next time you change the limit to LIMIT 50,50 (starting from element number 50 and query the 50 following elements).
The order depends on the fields you are making when the entries are inserted. Normally you can update your table and add the field created TIMESTAMP DEFAULT CURRENT_TIMESTAMP and then just use ORDER BY created, because from now on your entries will store the exact time they were created in order to look for the most recent ones (If you have an AUTO_INCREMENT id you can look for the greater values aswell).
This could be an example of this system using php and MySQL:
$page = 1;
if(!empty($_GET['page'])) {
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
if(false === $page) {
$page = 1;
}
}
// set the number of items to display per page
$items_per_page = 50;
// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM your_table LIMIT " . $offset . "," . $items_per_page;
I found this post really useful when I first try to make this pagination system, so I recommend you to check it out (is the source of the example aswell).
Hope this helped you and sorry I coudn't provide you a better example since I don't have your code.
Search for pagination using php & mysql. That may become handy with your problem.
To limit a mysql query to fetch 50 rows use LIMIT keyword. You may need to find & store the last row id(50th row) so that you can continue with 51th to 100th rows in the next page.
Post what you have done with your code. Please refer to whathaveyoutried[dot]com
check this example from another post https://stackoverflow.com/a/2616715/6257039, you could make and orber by id, or creation_date desc in your query

How to avoid getting duplicate posts from database in an "infinite scrolling" system?

I have an AJAX system that fetch posts from database and then create DIVs in my layout to put them. When te user reachs the end of the page then many other posts will be loaded by the API. The problem is, how can I get the following 10 posts that are just the previously posts of the last that is already loaded? The same thing I want to happen when I load the new posts at the top, how to show every post in the right order without missing any post or duplicating any post?
Sorry for the bad explanation and the bad english.
You need to store the id of the last retrieved message. When you submit the new request, send the last received message id and have php/mysql return the results from there.
If your query looks something like this:
SELECT * FROM posts WHERE username='redcurley' LIMIT 10
Then you'd need to modify to be something more like:
SELECT * FROM posts WHERE username='redcurley' AND id > :id LIMIT 10
You could alternatively use the offset method that Scott mentions.
Edit: I assumed you were using auto-increment ids because it's so common. Since you aren't, you need some way to keep track of the last message returned. You can do this through sorting the records in a way that they'll come out in the same order every time and use offsets.
You could probably use an OFFSET in your query, which would work even if you wanted to get results that may have out-of-order IDs. So if you had -
SELECT * FROM posts WHERE username='foo' LIMIT 10
The next query would be
SELECT * FROM posts WHERE username='foo' LIMIT 10 OFFSET 10
and so on like that as you fetch more and more records. Your Javascript would have to keep track of the offset and send it to the server with the AJAX request.
To allow near infinate results you can't use an AUTO_INCREMENT as there is eventually a limit.
What you can do though is when posted add a timestamp to the row and then in first load there is no timestamp given to the AJAX handle code so it gets them all and sends back the timestamp the query was run at then when it recives it it can then use a different query that has WHERE timestamp > $sentTimestamp
E.G
<?php
// AJAX handler code
$sqlQuery = "SELECT * FROM posts"
if(!empty($_REQUEST['lastPull'])){
$sqlQuery .= " WHERE `timestamp` > ".mysql_real_escape_string($_REQUEST['lastPull']);
}
// do your query and formatting for AJAX response here
?>
When user load page, You can fetch all last 10 post with page load,
for example -
id POST
1 Post1
2 Post2
3 Post3
.
.
.
10 Post10
So when user scroll page bottom, You will call your ajax code and pass you last id as input and make paggination using LIMIT in your SQL query.
For example -
My last post id is 50 and user scroll down page, So query will fire,
Select * from tableName where id < 50 LIMIT 10
This is for old post, and mean while if any new post then you can check new post using new query with last id at the time of user refresh page.
Select * from tableName where id > 50 LIMIT 10
This is for new post, return both collection in single request to page and by evaluating both you can inserts new div tag to show this.
You can use ajax and JSON combination, Click Here if you want more deail about JSON and AJAX.

Limit MySQL Query with Show More button

In PHP/AJAX, is there a straight forward way to display a certain number rows from a query (let's say 5) and then have a "show more" button that shows the next 5 (and so on)?
assuming you dont want to use AJAX (because you said "in PHP"): what you can do is use limit in your sql to get only the first few results. You can then generate the page and when you generate the "more" button, you add a query string to the page it has been sent to with something like ?begin=6 so your php script knows where to start.
assuming you are using AJAX: You can use jQuery's $.ajax() function (or any other library, or "raw" javascript, if you like pain) to get the results back with the same url scheme. then replace the content of the container with whatever results you get back.
SELECT info FROM table LIMIT 0,5 //First 5 results
SELECT info FROM table LIMIT 5,5 //Next 5 results
SELECT info FROM table LIMIT 10,5 //Next 5 results

PHP/MySQL Show first X results, hide the rest

Does anyone know how to bring in all of a mysql tables' results, only show the first X, (say 10), and then hide the rest using jquery? I just need to know how to show only the first X results in one page, then the rest in a seperate page using href.
My aim is to only show the first 10 results, but provide a link at the bottom of the page allowing the user to show all of the results. Was thinking the hyperlink could just re-execute the query but thought it would be easier to show/hide using jquery.Thanks
Rather than using jquery, you can use MySQL to retrieve only the desired results.
SELECT * FROM TableName LIMIT 10
That will retreive the first 10 results. Then, to display the next 10 on the next page,
SELECT * FROM TableName LIMIT 10 OFFSET 10
and the next page
SELECT * FROM TableName LIMIT 10 OFFSET 20
If you are using PHP, you can build your query to show the correct results depending on which page you are on:
// $currentPage is set elsewhere in the script, and is zero-based.
$resultsPerPage = 10;
$currentOffset = $resultsInPage * $currentPage;
$query = "SELECT * FROM TableName LIMIT $resultsInPage OFFSET $currentOffset";
Actually you are searching for Pagination. There are some useful jQuery paginations plugins:
jQuery pagination plugin
DataTables Plugin
Or using PHP:
Pagination in PHP
You need pagination look at the some tutorial to do this. there are lot of code examples on this do googling
here are some links
http://www.codediesel.com/php/simple-pagination-in-php/ -
http://php.about.com/od/phpwithmysql/ss/php_pagination.htm
It might be "easier", but it's a lot less resource efficient to load all the data (and then optionally show it) in the manner you're describing.
I'd really recommend using multiple queries (perhaps via Ajax/lazy loading) rather than using the approach you're discussing.
I'd do this with a LIMIT statement in the Select-statement of your SQL query. In most cases there's no need to send all the data to the client and then let javascript hide the data you don't wanna show.

Categories