My code below basically gets a bunch of films from the db and sets the year as the array key then echoes out each film per year. Thats all cool although my results are getting to long and need paginating. I cant find any examples that help my situation as most pagination in php is for while loops - appreciate any help or feedback.
I dont mind if its jquery or php or a combo of both.
<?php
require_once('Connections/timeline.php');
mysql_select_db($database_timeline, $timeline);
// select all the events from the database ordered by date:
$res = mysql_query("SELECT * FROM film2 ORDER BY `year` ASC");
$filmArray = null;
while($row_res = mysql_fetch_assoc($res)) {
$year = $row_res['year'];
$filmArray[$year][] = $row_res;
}
//for each year in the film array echo out each film within that year
foreach($filmArray as $year => $films) {
echo $year;
echo '<br />';
foreach($films as $film) {
echo $film['event'];
echo '<br />';
echo $film['name'];
echo '<br />';
}
}
?>
You need to have GET parameter, for example, page.
URL: localhost/film.php?page=1
And then
if (isset($_GET['page']))
$page = $_GET['page'];
else
$page = 1;
$entriesPerPage = 20;
$limitFrom = $page - 1;
$limitTill = $limitFrom + $entriesPerPage;
And then Your SQL query:
$res = mysql_query("SELECT * FROM film2 ORDER BY `year` ASC LIMIT $limitFrom, $limitTill");
And in the end, create html links.
Previous
Next
Related
I am trying to write a program of photoalbums in simple PHP, but i want to make it a little more advanced then i used to do.
Usually i wrote it like this:
<?php $query = mysql_query("SELECT year FROM photo");
while($record = mysql_fetch_object($query)) {
echo $record->year."<br>";
$query2 = mysql_query("SELECT albumName, url FROM photo WHERE year = '".$year."'");
while($album = mysql_fetch_object($query2)){
echo "".$albumName."<br>";
}
} ?>
As you would understand it's really bad to have two while loops in one, so i want to do it differently. I want to learn how to do this better. The thing is, I don't know a name for this so it's difficult to search on this subject. Is there anyone able to hand me a snippet of code, a source or something to get me on the way?
Thank you so much.
You could do
<?php
$year = ''; // create a generic variable that will hold the album year
$query = mysql_query("SELECT albumName, url, year FROM photo ORDER BY year"); // Sort by year
while($album = mysql_fetch_object($query)) {
if($album->year != $year){ // check if $album->year is the same as the $year value
echo $album->year."<br>"; // if not the same echo the year
}
$year = $album->year; // set the $year value to the $album->year
echo "".$album->albumName."<br>";
}
?>
What if you do this:
<?php $query = mysql_query("SELECT albumName, url, year FROM photo");
while($record = mysql_fetch_object($query)) {
echo $record->year."<br>";
echo "".$albumName."<br>";
}
?>
What would be wrong?
Now your code might produce an album more than one times, if there are many albums per year.
How to split the search results into pages? (like page 1, page 2, page 3...)
When the user searches for products on my e-commerce website, I want results to be split into several pages showing around 20 products per page. The search results are the outcome of database query.
For example: If the user searches for Samsung mobiles so my query will be:
SELECT * FROM PRODUCTS WHERE BRAND='SAMSUNG';
Suppose the above query returns 55 results, how to show them into pages (1,2 and 3)?
I am using PHP, MySQL, Apache on Windows machine.
The appropriate SQL would be adding:
LIMIT start, amount
You can navigate like
search.php?start=20
and then code like:
LIMIT $start, $amount
with
$start = intval($_GET['start']);
and
$amount = 20;
That will result in max 20 records a page.
Use SQL's LIMIT keyword to limit the amount of results from your query; for example:
SELECT * FROM PRODUCTS WHERE BRAND='SAMSUNG' LIMIT 20, 40;
This would select 20 elements, starting at the 40th
Here is the complete code:
<?php
// Requested page
$requested_page = isset($_GET['page']) ? intval($_GET['page']) : 1;
// Get the product count
$r = mysql_query("SELECT COUNT(*) FROM PRODUCTS WHERE BRAND='SAMSUNG'");
$d = mysql_fetch_row($r);
$product_count = $d[0];
$products_per_page = 20;
// 55 products => $page_count = 3
$page_count = ceil($product_count / $products_per_page);
// You can check if $requested_page is > to $page_count OR < 1,
// and redirect to the page one.
$first_product_shown = ($requested_page - 1) * $products_per_page;
// Ok, we write the page links
echo '<p>';
for($i=1; $i<=$page_count; $i++) {
if($i == $requested_page) {
echo $i;
} else {
echo ''.$i.' ';
}
}
echo '</p>';
// Then we retrieve the data for this requested page
$r = mysql_query("SELECT * FROM PRODUCTS WHERE BRAND='SAMSUNG' LIMIT $first_product_shown, $products_per_page");
while($d = mysql_fetch_assoc($r)) {
var_dump($d);
}
?>
Hope its help.
Yes you can run a query to get total record count and than use query using limit
exampe:
select count(id) from table_name
This will return total record count in database
In my php learning books, it provides a solution using a PHP class
it looks like this
<!-- language: php -->
<?php
error_reporting(0); // disable the annoying error report
class page_class
{
// Properties
var $current_page;
var $amount_of_data;
var $page_total;
var $row_per_page;
// Constructor
function page_class($rows_per_page)
{
$this->row_per_page = $rows_per_page;
$this->current_page = $_GET['page'];
if (empty($this->current_page))
$this->current_page = 1;
}
function specify_row_counts($amount)
{
$this->amount_of_data = $amount;
$this->page_total=
ceil($amount / $this->row_per_page);
}
function get_starting_record()
{
$starting_record = ($this->current_page - 1) *
$this->row_per_page;
return $starting_record;
}
function show_pages_link()
{
if ($this->page_total > 1)
{
print("<center><div class=\"notice\"><span class=\"note\">Halaman: ");
for ($hal = 1; $hal <= $this->page_total; $hal++)
{
if ($hal == $this->current_page)
echo "$hal | ";
else
{
$script_name = $_SERVER['PHP_SELF'];
echo "$hal |\n";
}
}
}
}
}
?>
then we call it on the script that require paging
<!-- language: php -->
<?php $per_page = 5;
$page = new Page_class($per_page);
error_reporting(0); // disable the annoying error report
$sql="SELECT * FROM table WHERE condition GROUP BY group";
$result=mysql_query($sql) or die('error'.mysql_error());
// paging start
$row_counts = mysql_num_rows($result);
$page->specify_row_counts($row_counts);
$starting_record = $page->get_starting_record();
$sql="SELECT * FROM table WHERE condition GROUP BY group LIMIT $starting_record, $per_page";
$result=mysql_query($sql) or die('error'.mysql_error());
$number = $starting_record; //numbering
$num_rows = mysql_num_rows($result);
if ($num_rows == 0 )
{ // if no result is found
echo "<div class=\"notice\">
<center><span class=note>NO DATA</span></center>
</div>";
}
else {
// while goes here ...
}
?>
// call the page link
<?php
$page->show_pages_link();
?>
hope it helps, just tried it hours ago to my search script page (learning from books)
Hey, I want to add a button(link), that when clicked will filter the pagination results.
I'm new to php (and programming in general) and would like to add a button like 'Automotive' and when clicked it updates the 2 mysql queries in my pagination script, seen here:
As you can see, the category automotive is hardcoded in, I want it to be dynamic, so when a link is clicked it places whatever the id or class is in the category part of the query.
1:
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='automotive'"));
2:
$get = mysql_query("SELECT * FROM explore WHERE category='automotive' LIMIT $start, $per_page");
This is the entire current php pagination script that I am using:
<?php
//connecting to the database
$error = "Could not connect to the database";
mysql_connect('localhost','root','root') or die($error);
mysql_select_db('ajax_demo') or die($error);
//max displayed per page
$per_page = 2;
//get start variable
$start = $_GET['start'];
//count records
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='automotive'"));
//count max pages
$max_pages = $record_count / $per_page; //may come out as decimal
if (!$start)
$start = 0;
//display data
$get = mysql_query("SELECT * FROM explore WHERE category='automotive' LIMIT $start, $per_page");
while ($row = mysql_fetch_assoc($get))
{
// get data
$name = $row['id'];
$age = $row['site_name'];
echo $name." (".$age.")<br />";
}
//setup prev and next variables
$prev = $start - $per_page;
$next = $start + $per_page;
//show prev button
if (!($start<=0))
echo "<a href='pagi_test.php?start=$prev'>Prev</a> ";
//show page numbers
//set variable for first page
$i=1;
for ($x=0;$x<$record_count;$x=$x+$per_page)
{
if ($start!=$x)
echo " <a href='pagi_test.php?start=$x'>$i</a> ";
else
echo " <a href='pagi_test.php?start=$x'><b>$i</b></a> ";
$i++;
}
//show next button
if (!($start>=$record_count-$per_page))
echo " <a href='pagi_test.php?start=$next'>Next</a>";
?>
Example with 2 links/categories:
<a href='script.php?category=automotive'>automotive</a> <a href='script.php?category=sports'>sports</a>
Inside script.php:
$category = mysql_real_escape_string($_GET['category']);
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='$category'"));
...
$get = mysql_query("SELECT * FROM explore WHERE category='$category' LIMIT $start, $per_page");
Edit: I only posted this answer in response to the OP stating he was new to programming. Good hygiene is learned at the beginning very easily and becomes habit, or much later and is very hard to make habit.
http://us2.php.net/manual/en/security.database.sql-injection.php
please also read this article on security for databases. It would be much improved to write your queries as:
$start = mysql_real_escape_string($_GET['start']);
settype($start, 'integer');
$category = mysql_real_escape_string($_GET['category']);
$record_count = mysql_num_rows(mysql_query("SELECT * FROM explore WHERE category='%s'", $category));
...
$get = mysql_query("SELECT * FROM explore WHERE category='%s' LIMIT %d, %d", $category, $start, $per_page);
It is always worth it to write the extra secure code, even if just for practice. Basic security rules for databases are: Never trust user input, always check generated output. Since the input is from a querystring and gets run against the database, it has to be filtered.
I will try to be as clear as possible because I can't get anybody to help me around,
I am trying to associate some data from a 'videos' table with their respective ID.
Lets say, I have column ID, title, serie, season, episode.
I am getting my data :
<?
$result = mysql_query("SELECT * FROM videos WHERE serie = '".$row['serie']."' AND season = '".$row['season']."'");
$total_rows = mysql_num_rows($result);
?>
(that is in the page where you see the video itself)
So now I can get the number of episodes from a serie and season.
What I'm trying to do is have a link for the next episode, and aa link for the previous one. In the URL I am working with the id, so http://website.com/view/id/'video id here'/
So how can I get the ID of the following and previous episodes of the same season AND serie?
Help will be much appreciated!
The easiest thing I thought of is
<?=$row['id'] + 1?>
<?=$row['id'] - 1?>
But the thing is that it's mixed videos, so it wont work 100%
I think you've taken my example too literally. I'll post a complete example in the morning (I'm just replying from my iPhone at the mo). For some reason it wouldn't let me add a comment to your last reply, so sorry this is as an answer.
[edit] here's a more complete example:
<?php
$result = mysql_query("SELECT * FROM videos WHERE series='$series' AND season = '$season'");
$last_row = null;
$next_row = null;
$current_id = $_GET['id'];
while($row = mysql_fetch_assoc($result)) {
if($current_id == $row['id']) {
$next_row = mysql_fetch_assoc($result);
break;
}
$last_row = $row;
}
if($last_row != null) {
echo "<a href='?id={$last_row['id']}'>Prev</><br/>\n";
}
if($next_row != null) {
echo "<a href='?id={$next_row['id']}'>Next</><br/>\n";
}
?>
A few things to note:
This is untested.
In your initial example, I didn't know where you were getting the $row['serie'] and $row['season'], so in my example, I've just used the variables $series and $season. You'll have to fill these in with what you want the current result set to be filtered by.
For my example, the URL format uses the GET layout (ie. ?id=).
If you do:
$results = mysql_query($sql);
(where $sql is your mentioned select statement)
Then the $results array will contain all results of that series/season.
So you can access it via:
$previous = $results[$n - 1];
$next = $results[$n + 1];
$previous_id = $previous['id'];
$next_id = $next['id'];
Note that you'll of course need to check that $n - 1 isn't less than zero, and ($n + 1) isn't greater than your $total_rows.
Here is what I tried, I guess it is what you meant,
All that it's doing is put the previous episode, so I get /view/id/3/ (if the episode i am watching is 4)
<?
$result = mysql_query("SELECT * FROM videos WHERE serie = '".$row['serie']."' AND season = '".$row['season']."'");
$total_rows = mysql_num_rows($result);
$previous = $results[$n - 1];
$next = $results[$n + 1];
$previous_id = $previous['id'];
$next_id = $next['id'];
?>
<? if($row['episode'] == 1) { ?>
<td align="center" width="33%"></td>
<? } else { ?>
<td align="center" width="33%"><img src="images/previous.gif" srcover="images/previoush.gif" alt="Previous Video" border="0" /></td><? } ?>
That is only for the previous one,
Sorry I had to post like this, if not it wouldnt have appeared correctly,
(Correct me if I'm wrong with the code)
And thanks for the reply
Here's what I've got so far-
$awards_sql_1 = mysql_query('SELECT * FROM categories WHERE section_id = 1') or die(mysql_error());
$awards_sql_2 = mysql_query('SELECT * FROM categories WHERE section_id = 2') or die(mysql_error());
$awards_sql_3 = mysql_query('SELECT * FROM categories WHERE section_id = 3') or die(mysql_error());
$awards_sql_4 = mysql_query('SELECT * FROM categories WHERE section_id = 4') or die(mysql_error());
$loop = 1;
while($row_sections = mysql_fetch_array($sections_query)) {
$category = 1;
echo "<h3>" . $row_sections['section_name'] . " (Loop# $loop)</h3>";
while($categories = mysql_fetch_array(${"awards_sql_{$loop}"})) {
${"winners_sql_{$loop}"} = mysql_query("SELECT * FROM 2009_RKR_bestof WHERE section = $loop && category = $category ORDER BY result_level ASC") or die(mysql_error());
echo "<h4><strong>{$categories['category_name']}</strong></h4>";
echo "<ul class=\"winners\">";
>> while($winners = mysql_fetch_array(${"winners_sql_{$loop}"})) {
switch ($winners['result_level']) {
case 1: $result_level = "Platinum"; break;
case 2: $result_level = "Gold"; break;
case 3: $result_level = "Silver"; break;
}
if (isset($winners['url'])) { $anchor = ""; $close = ""; }
echo "<li>$anchor{$winners['winner']}$close ($result_level)</li>";
unset($anchor);
unset($close);
}
echo "</ul>";
$category++;
}
$loop++;
}
Where I'm getting stumped, is I'm getting this thing to loop through correctly, my loop counter ($loop) is working, but when it gets time to spit out the actual reward recipients after the first loop through winners, it's only producing the category titles, the list-items are not getting looped out.
I added a little pointer to where I think the problem begins or centers around (>>).
My guess is I need to maybe unset a var somewhere, but I don't know, I can't see it.
I'm with KM - you're displaying a single page and with your loops, you've got a LOT of queries happening at once - what if 1,000 people hit that page at the same time? ouch...
Maybe consider a larger query (with some repeated data) and loop through it once?
For example:
SELECT
section_name,
category_name,
result_level,
url,
winner
FROM 2009_RKR_bestof
INNER JOIN categories ON 2009_RKR_bestof.category = categories.id
INNER JOIN sections ON 2009_RKR_bestof.section = sections.id
ORDER BY section_name,category_name ASC
In your loop, you can do checks to determine if you're in a new section (category/whatever):
//pseudo-code
$current_section = "";
while($stuff = mysql_fetch_array($sql))
{
if ($current_section == "")
{
$current_section = $stuff["section_name"];
}
if ($current_section == $stuff["section_name"])
{
//keep going in your loop
}
else
{
//we've gotten to a new section - so close your html and start a new section
}
}
You get the idea..
My guess would be that it is a data problem. It isn't having trouble reading the titles, only the winners. If it iterated once, I would check the data, and ensure that winners_sql_2 - winnders_sql_4 are getting actual data. Perhaps add an echo winners_sql_2 line, to output the contents of the query, and ensure the query is framed correctly.