TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
IRC Channel
IRC Speech Bubble Join the friendly bunch on IRC...
(#TalkPHP on Freenode)

...Also available via a web interface.

See this thread for information on the TalkPHP Free Hugs Initiative™. Subject to availability.
Associates
Associates
CSS Tutorials
Reply
 
LinkBack (1) Thread Tools Search this Thread Display Modes
Old 12-14-2007, 08:32 PM   1 links from elsewhere to this Post. Click to view. #1 (permalink)
The Acquainted
Upcoming Programmer 
 
CMellor's Avatar
 
Join Date: Sep 2007
Location: Leeds, UK
Posts: 141
Thanks: 6
CMellor is on a distinguished road
Bug Pagination, Funtions, Converting

Pagination, a topic that's arose a lot at this website this past week, lol, now I'm adding to it

With all the topics that have arose this past week, it got me thinking that pagination is something I haven't yet put into parts of my project that are finished, so I've decided to get to work on it. Previously when I was working on a project, I was lazy and used someone else's code, but no longer will I do that, with anything, how else will I learn? I've found a really easy tutorial at Pixel2Life that I'm using as a guideline, and I also plan on using some code that was posted here to shorten the numbered links.

Here's the code I've got, which works great!

php Code:
<?php
include('configs/functions.php');

// Check if page is set
$page = isset($_GET['page']) ? $_GET['page'] : 1;

// Set maximum number of results to return
$max = 2;

// Calculate what page number their on
$res = ceil(($page * $max) - $max);

// Get the data you require from the database
$query = mysql_query(sprintf("
    SELECT * FROM poll_options
    ORDER BY poll_options_id DESC
    LIMIT %d, %d"
,
        $res,
        $max
)) or die(mysql_error());
// Fetch the data
while($row = mysql_fetch_array($query)) {
    echo $row['choice'].'<br />';
}

// Count how many results are in the table
$count_query = mysql_query("
    SELECT * FROM poll_options"

) or die(mysql_error());
// Count the total
$total = mysql_num_rows($count_query);

// How many pages will there be?
$total_pages = ceil($total / $max);

/* Work out the number of links needed */
// If page number is more than 1...
if($page > 1) {
    // Take one away from the current page number
    $prev = ($page - 1);
    // Print a 'previous' link
    $links = '<a href="?page='.$prev.'">&laquo; Previous</a> ';
}
// Page numbers
for($i = 1; $i <= $total_pages; $i++) {
    // If page number is same as current number
    if($page == $i) {
        $links .= '<strong>'.$i.'</strong> ';
    }
    else {
        $links .= '<a href="?page='.$i.'">'.$i.'</a> ';
    }
}
// Work out if theirs a next page
if($page < $total_pages) {
    // Increment from the page number
    $next = ($page + 1);
    // Print a 'next' link
    $links .= '<a href="?page='.$next.'">Next &raquo;</a>';
}

echo $links;
?>
This will go in my 'functions.php' file, and I want to use the same functions for different queries to paginate. I thought of splitting that code into two functions, and keeping the query seperate, like so...

php Code:
<?php
include('configs/functions.php');

function results($max_num) {
    global $max;
    // Check if page is set
    $page = isset($_GET['page']) ? $_GET['page'] : 1;
   
    // Set maximum number of results to return
    $max = $max_num;
   
    // Calculate what page number their on
    $res = ceil(($page * $max) - $max);
   
    return $res;
}

function pagiLinks() {
    global $max;
    // Count how many results are in the table
    $count_query = mysql_query("
        SELECT * FROM poll_options"

    ) or die(mysql_error());
    // Count the total
    $total = mysql_num_rows($count_query);
   
    // How many pages will there be?
    $total_pages = ceil($total / $max);
   
    /* Work out the number of links needed */
    // If page number is more than 1...
    if($page > 1) {
        // Take one away from the current page number
        $prev = ($page - 1);
        // Print a 'previous' link
        $links = '<a href="?page='.$prev.'">&laquo; Previous</a> ';
    }
    // Page numbers
    for($i = 1; $i <= $total_pages; $i++) {
        // If page number is same as current number
        if($page == $i) {
            $links .= '<strong>'.$i.'</strong> ';
        }
        else {
            $links .= '<a href="?page='.$i.'">'.$i.'</a> ';
        }
    }
    // Work out if theirs a next page
    if($page < $total_pages) {
        // Increment from the page number
        $next = ($page + 1);
        // Print a 'next' link
        $links .= '<a href="?page='.$next.'">Next &raquo;</a>';
    }
   
   
    return $links;
}

// Call function to get results
results(2);

// Get the data you require from the database
$query = mysql_query(sprintf("
    SELECT * FROM poll_options
    ORDER BY poll_options_id DESC
    LIMIT %d, %d"
,
        $res,
        $max
)) or die(mysql_error());
// Fetch the data
while($row = mysql_fetch_array($query)) {
    echo $row['choice'].'<br />';
}

echo pagiLinks();
?>
This only displays two results and shows numbered links and a next link (but no previous link) and when you change the page number, it doesn't show the other rows. I know this is because with some of the important code been in functions, that $res and $max equal 0. Can you even use a variable stored inside a function, outside of the function, by just say echo'ing it out?

I thought that putting the code in those two functions like I have would save me time in re-writing the code over and over when I wanted to paginate some queries.

Hope I make some sense to you, and any help I get, like always would be appreciated!

P.S. I don't use classes in this project, so if you could avoid any solutions using classes, that'd be great
__________________
Not quite a n00b...
CMellor is offline  
Reply With Quote
Old 12-15-2007, 01:01 AM   #2 (permalink)
The Frequenter
Newcomer 
 
xenon's Avatar
 
Join Date: Dec 2007
Location: Bucharest, Romania
Posts: 438
Thanks: 3
xenon is on a distinguished road
Default

Quote:
Originally Posted by CMellor View Post
Can you even use a variable stored inside a function, outside of the function, by just say echo'ing it out?
You can't do that. This is not a valid code:

Code:
function test()
{
    $x = 4;
}

echo $x; // WRONG
Not even this works:

Code:
$x = 4;

function test()
{
    $x++;
}

test(); // will throw a notice about an undefined variable use
__________________
I have optimistic thoughts, even though sometimes (if not always) life's a bitch.
xenon is offline  
Reply With Quote
Old 12-23-2007, 11:53 PM   #3 (permalink)
The Contributor
 
Join Date: Feb 2007
Posts: 64
Thanks: 9
Killswitch is on a distinguished road
Default

Quote:
Originally Posted by xenon View Post
You can't do that. This is not a valid code:

Code:
function test()
{
    $x = 4;
}

echo $x; // WRONG
Not even this works:

Code:
$x = 4;

function test()
{
    $x++;
}

test(); // will throw a notice about an undefined variable use
Instead, you could return the value or have the function itself echo the variable value ( I would much prefer to return the value ). You would also want to pass variables into your function if you want to use them inside it (you could always global a variable, but you really want to avoid this).

Code:
function test()
{
    $x = 4;
    return $x;
}
Another example

Code:
$x = 4;

function test( $x ) 
{
    $x++; 
     return $x;
}
Dunno if its of anyhelp, but there it is
Killswitch is offline  
Reply With Quote
Old 10-18-2012, 12:55 PM   #4 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default

Some conservatives have Coach Factory Outlet pushed that critique further, saying that Mr. Obama’s policies are too costly, often assist the wrong people Louis Vuitton Belts and could have the paradoxical effect of driving up college costs. The dispute turns not just on different Coach Factory Outlet assessments of how policies play out, but on differing philosophical views about the role of government. During Gucci Belts his time in office, Mr. Obama has sharply increased aid to low- and middle-income students, notably through the Pell Grant Coach Factory Outlet program, which grew from $14.6 billion given to 6 million students in 2008, to nearly $40 billion for Coach Factory Outlet almost 10 million students this year. His administration also made it easier to request aid, shortening the Coach Factory Online complex federal application and allowing people to transfer their financial information electronically from the Internal Coach Outlet Online Revenue Service database. But while many education experts laud his efforts, analysts of varying political Coach Outlet Online stripes have also questioned how much impact some of the president’s policies will have, noting that the prices Coach Online Outlet charged by colleges, and student borrowing, continue to climb.But behind the headlines about soaring costs, the Coach Factory Outlet Online reality is more complex and wildly uneven, because a growing number of students receive Coach Outlet Online financial aid, and only relatively high-income families pay those fast-rising sticker prices. Adjusted for Coach Factory Online inflation, the College Board calculates, the average net price changed little over the last decade at private Coach Factory Outlet schools, and rose only modestly at public ones.Defending federal spending, Arne Duncan, the secretary of Hermes Belts education, said that for more than 30 years, college prices had risen even when federal aid had not, leading him to believe Coach Factory Online there was zero correlation.
dashixiong is offline  
Reply With Quote
Old 10-22-2012, 09:11 AM   #5 (permalink)
The Addict
 
Join Date: Oct 2012
Posts: 244
Thanks: 0
dashixiong is on a distinguished road
Default Coach Outlet

You’ve relativelyCoach Outlet recently arrived in New Delhi after living in two of Asia’s other great cities,Coach Outlet Store Online Tokyo and Hong Kong, for several years. Do these cities feel like they’re part of the same continent? Yes, and no. In terms Coach Factory Onlineof infrastructure, they couldn’t be more different. Getting regularCoach Outlet power and water at my house in New Delhi is never a sure thing, even though Coach Purse Outlet OnlineI’m paying the same rent that I paid in Tokyo and almost the same electricity prices. Both Hong Kong and Tokyo are also crowded places,Coach Factory Outlet Online but both cities are incredibly well planned and efficiently run. Efficient is not a word I would use to describe my Coach Bags Outlet Onlineday-to-day life in New Delhi. On the other hand, one thing that I think Hong Kong and New Delhi have in common isCoach Handbags Outlet a shared sense of optimism — a feeling that the best is yet to come. That’s definitely not the feeling you get in Tokyo,Coach Outlet Online or in the U.S. when I go home. It’s a big part of what I find addictive about living and working in this part of the world. You feel like you’re watching the future unfold.
dashixiong is offline  
Reply With Quote
Reply


LinkBacks (?)
LinkBack to this Thread: http://www.talkphp.com/absolute-beginners/1738-pagination-funtions-converting.html
Posted By For Type Date
TalkPHP - Powered by vBulletin This thread Refback 12-24-2007 01:44 AM

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 12:48 PM.

 
     

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0
Inactive Reminders By Icora Web Design