I am pulling some data from mysql database using PHP, now I would like to place that data in a html table which I have completed, how can I make the table pageable if it goes over say 10 records? Is there a tutorial I can look into or any information where I can get this? Maybe a tool I can implement easily? I just haven't found anything online about this topic but perhaps anyone here can lead me in the correct direction
I am currently using just a simple <table></table> html
You can achieve paging with MySQL's LIMIT keyword.
You can then use a query string to tell the website which page to get.
First we need to set a default page number and define how many results we want to display in the page:
$items_per_page = 10;
$page = 1;
if(isset($_GET['page'])) {
$page = (int)$_GET['page'];
}
The LIMIT keyword works by providing an offset and the number of rows you want to limit to. So now we need to figure out the offset:
$offset = ($page - 1) * $items_per_page;
Now we have all of the information we need to limit the results correctly based on the page number in our query string:
$query = "SELECT column_1, column_2 FROM your_table LIMIT {$offset}, {$items_per_page};";
$result = mysql_query($query) or die('Error, query failed');
while($row = mysql_fetch_assoc($result)) {
echo $row['column_1'] . '<br />';
}
Now to show your different pages you just add the query string to the end of your page URI.
For example my_page.php?page=1 or my_page.php?page=2
Perhaps you could try to figure out how to create the paging links by yourself and post more if you can't get it to work.
You just need to find out the total rows in your query with COUNT in MySQL and you can do all of the maths from there ;)
You'll need some javascript in order to do paging..
Take a look at http://flexigrid.info/
In summary, what you should do is have your php script return the tabular data as JSON or XML, and then feed it to flexgrid.
You can also have flexgrid request records when they're needed using additional requests.
Related
i'm struggling with adding pagination with php to my search results. Currently I search on index.php for a term and it takes me to search.php with a list of results that match from my database. This part works fine but i'd like it to show 10 results per page rather than every result on the same page. How do I achieve this? I've taken a look here and here but my code is a little different and i'm struggling to implement the suggestions. Any help would be greatly appreciated, even if to just point me in the correct direction.
<?php
if (isset($_POST['submit-search'])) {
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM people WHERE location LIKE '%$search%'";
$result = mysqli_query ($conn, $sql);
$queryResult = mysqli_num_rows($result);
echo " ".$queryResult." RESULTS";
if ($queryResult > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<div>
<h3>".$row['firstname']."</h3>
<p>".$row['lastname']."</p>
<p>".$row['location']."</p>
<p>".$row['profession']."</p>
</div>";
}
}
}
?>
I will explain the logic here and give you the link in which the pagination is implemented.
In your present code, you are fetching all the results from the DB and displaying it in the template.
What you should actually do is make use of the MySQL's LIMIT clause, and fetch the results in batches.
LIMIT clause can be used like below:
SELECT * FROM people WHERE location LIKE '%$search%' LIMIT 5, 10
Where 5 is OFFSET and 10 is Row Count. That is, the above query only fetches the result from 5 to 15 (Given the rows are continuous ids).
More info on: MYSQL LIMIT
Now, you can think OFFSET as Current page * Number of people listed on a page and Row Count as Number of people listed on a page (constant).
So, for the first page you will use the following query:
SELECT * FROM people WHERE location LIKE '%$search%' LIMIT 0, 10
Where,
Current page = 0 * 10;
number of people listed in a page = 10;
For the second page:
SELECT * FROM people WHERE location LIKE '%$search%' LIMIT 10, 10
Current page = 1*10;
number of people listed in a page = 10;
and so on... The only variable that changes here is the page, which you can request through URL.
I will add the link to a github repo which implements this logic. Please go through that and understand the working.
Repo: PHP Pagination
I'm a beginner who has problems with PHP :(
I have a PHP function which shows all the rows from the database table. Now I have to create paging to show only limited number of rows per one page.
I have a problem with retrieving a COUNT result from query. I want to create a condition where PHP & MySQL use LIMIT if number of rows is bigger than needed on one page. The following code:
$count = "SELECT COUNT(*) FROM articles";
$countq = $db->query($count);
$countrs = mysql_fetch_array($countq);
echo $countrs;
should display a number of rows. However, it does not. What am I doing wrong? I want to see a result to make sure that everything else will work fine. But I can't get it working.
Error: mysql_fetch_array() expects parameter 1 to be resource, object given
$db contains database connection information (server, user...) and is working
Use PDO for MySQL query.
$db = new PDO('mysql:host=#YOUR HOST#;dbname=#YOUR DB#;charset=utf8', '#YOUR LOGIN#', '#YOUR PASSWORD#');
$query = $db->query('SELECT COUNT(*) AS count FROM articles');
$countq = $query->fetch();
$query->closeCursor();
echo $countq['count'];
I hope this will help you
You will have to set the limit in the query like
$count = "SELECT COUNT(*) FROM articles LIMIT 5,10";
where 5 is the starting point and 10 is the total number of results you want.
You mention: $db but not what $db is? i mean is it a database object class? this will work directly if you are using the a database class, and if that's the case the class will also have functions which will allow you to query data without using mysql_fetch_array (actually mysqli_fetch_array).
I wrote a PHP/MySQLi frontend, in which the user can enter SQL queries, and the server then returns the results in a table (or prints OK on INSERTs and UPDATEs)
As printing the results can take a very long time (e.g. SELECT * FROM movies) in a IMDb extract with about 1.6M movies, 1.9M actors and 3.2M keywords, I limited the output to 50 rows by cancelling the printing for-loop after 50 iterations.
However, the queries themselves also take quite some time, so I hoped that it might be possible to set a global maximum row return value, nevertheless whether the LIMIT keyword is used or not. I only intended to use the server for my own practice, but as some people in my class are struggling with the frontend provided by the teacher (Windows EXE, but half of the class uses Mac/Linux), I decided to make it accessible to them, too. But I want to keep my Debian VM from crashing because of - well, basically it would be a DDoS.
For clarification (examples with a global limit of 50):
SELECT * FROM movies;
> First 50 rows
SELECT * FROM movies LIMIT 10;
> First 10 rows
SELECT * FROM movies LIMIT 50,100;
> 50 rows (from 50 to 99)
Is there any possibility to limit the number of returned values using either PHP/MySQLi or the MySQL server itself? Or would I have to append/replace LIMIT to/in the queries?
You can use there queries and add "LIMIT 50" to it.
And if they added LIMIT by them self just filter it out with regex and still add your LIMIT.
I believe you have to build yourself a paginator anyway, avoiding to use LIMIT statement is not really possible i believe.
Here is what I would suggest for a Paginator:
if($_REQUEST['page'] == ""){
$page = 1;
}else{
$page = $_REQUEST['page']; // perhaps double check if numeric
}
$perpage = 50;
$start = ($page - 1) * $perpage;
$limit_string = " LIMIT ". $start . "," . $perpage ;
$query = "SELECT * FROM movies";
$query .= $limit_string;
Hope that helps
You can create a function.
https://dev.mysql.com/doc/refman/5.0/en/create-function.html
Let us know if this helps.
I have a pagination, with limit 10 for example. If I'm on page 2 and click on sort, I'd like to sort just the records shown on the current pagination page; when I come back to page 1 I'd like the records to be sorted as they were before I sorted the 2nd page. Any tips how this can be achieved?
Maybe something like this:
if ($page == 1){
$result = mysql_query("SELECT * FROM users ORDER BY $orderby $sort LIMIT $start, $perpage");
} else {}
But for the ELSE I don't know how to limit just the 10 records from the current page.
Have you tried storing the current pages records in a javascript array and sorting it on the client?
Every time when you click next or previous page or while sorting, pass sort details as well as page details through url and get those in page and use those in your query .
No Mysql tagged here, so in php you could try
$arr contains all data from users-table
// on every page you slice the original array $page_num = 2, $amount_of_items_per_page = 10
$page_arr = array_slice($arr, $page_num*$amout_of_items_per_page, $amout_of_items_per_page);
Then if you want to sort somehow, you have to sort $page_arr.
sort ($page_arr);
ksort($page_arr);
I made a simple search box on a page, where a user can type in keywords to look for photos of certain items, using PHP. I'm using an MySQL database. I trim the result and show only 10 to make the loading quicker, but certain set of keywords causes the browser to hang on both IE and Firefox. When this happens on IE, I can see outlines of photos (just the silhouette) beyond the 10 results with an "X" mark at the top right corner, similar to when you load a photo and the photo doesn't exist on a webpage, even though I wrote the code to show only 10 results. The database has over 10,000 entries, and I'm thinking maybe it's trying to display the entire set of photos in the database. Here are some code that I'm using.
I'm using the function below to create the query. $keyword is an array of the keywords that the user has typed in.
function create_multiword_query($keywords) {
// Creates multi-word text search query
$q = 'SELECT * FROM catalog WHERE ';
$num = 0;
foreach($keywords as $val) { // Multi-word search
$num++;
if ($num == 1) {
$q = $q . "name LIKE '%$val%'"; }
else {
$q = $q . " AND name LIKE '%$val%'";}
}
$q = $q . ' ORDER BY name';
return $q;
//$q = "SELECT * FROM catalog WHERE name LIKE \"%$trimmed%\" ORDER BY name";
}
And display the result. MAX_DISPLAY_NUM is 10.
$num = 0;
while (($row = mysqli_fetch_assoc($r)) && ($num < MAX_DISPLAY_NUM)) { // add max search result!
$num++;
print_images($row['img_url'], '/_', '.jpg'); // just prints photos
}
I'm very much a novice with PHP, but I can't seem to find anything wrong with my code. Maybe the way I wrote these algorithms are not quite right for PHP or MySQL? Can you guys help me out with this? I can post more code as necessary. TIA!!
Don't limit your search results in PHP, limit them in the SQL query with the LIMIT keyword.
As in:
select * form yourtable where ... order by ... limit 10;
BTW, those LIKE '%something%' can be expensive. Maybe you should look at Full text indexing and searching.
If you want to show a More... link or something like that, one way of doing it would be to limit your query to 11 and only show the first ten.
Apart from the LIMIT in your query, I would check out mysql full text search (if your tables have the MyISAM format).
Why don't use use MySQL to limit the number of search results returned?
http://dev.mysql.com/doc/refman/5.0/en/select.html
add LIMIT to your query.
you are retrieving all rows from DB (lot of bytes traveling from DB to server) and then you are filtering the first 10 rows.
try
$q = $q . ' ORDER BY name LIMIT 10';
LIKE is slow also according to Flickr(slides 24-26). You should first try to use FULL TEXT indexes instead. If your site still seems slow there are also some other really fast(er)/popular alternatives available:
sphinx
elasticsearch
solr
The only thing that is a little bit annoying that you need to learn/install these technologies, but are well worth the investment when needed.