Jump to content

after adding isset($_get pagination not working


hakim

Recommended Posts

soory guys .. actually i am trying to add pagination in script.. but its not pagging.

but when i tried without isset($_get the code worked fine and then i tried to doing with isset($_get for a perticular cat

but its not working. can someone see my code and tell me whats worng i have done.

 

<!DOCTYPE HTML>
<html>
    <head>
        
        
    </head>
<body>

<?php
// include database connection
include 'libs/db_connect.php';

// page is the current page, if there's nothing set, default is page 1
$page = isset($_GET['page']) ? $_GET['page'] : 1;

// set records or rows of data per page
$recordsPerPage = 1;

// calculate for the query LIMIT clause
$fromRecordNum = ($recordsPerPage * $page) - $recordsPerPage;

// select all data
$query = "SELECT
            *
        FROM
            posts
        ORDER BY
            post_id desc
        LIMIT
            {$fromRecordNum}, {$recordsPerPage}";
            
            /*
            page and its LIMIT clause looks like:
            1 = 0, 5
            2 = 5,10
            3 = 10,15
            4 = 15, 20
            5 = 20, 25
            */
        
$stmt = $con->prepare( $query );
$stmt->execute();

//this is how to get number of rows returned
$num = $stmt->rowCount();

//check if more than 0 record found
if($num>0){
    $cat=1;
    
    if(isset($_GET['cat'])){
                        $cat_id = $_GET['cat'];
                        $get_posts = "select * from posts where category_id = '$cat_id'";
                        $run_posts = mysql_query($get_posts);
                        while($row_posts = mysql_fetch_array($run_posts)){
                            $post_id = $row_posts['post_id'];
                            $post_title = $row_posts['post_title'];
                            $post_date = $row_posts['post_date'];
                            $post_author = $row_posts['post_author'];
                            $post_image = $row_posts['image'];
                            $post_content = substr($row_posts['post_content'],0,80);
                            
                            echo "
                            <div class='post_area'>
                            
                            <h4>
                                <a href = 'details.php?post=$post_id'>$post_title</a>
                            </h4>
                            <div class='date'><div id='com'> Date</div>$post_date</div><span style='font-size:12px'><i style='color:grey;font-size:10px'>Posted By</i> </b>$post_author</span>
                            
                            
                            <content><img src = '123dondadatest/news_images/$post_image' width = '100' height='100'/>
                            <div>$post_content <br/><a id='rmlink' href = 'details.php?post=$post_id'> Read More...</a></div><br /><br/><br/><br/>
                            
                            </div>
                            
                            ";
                            }
                    }

    
    // *************** <PAGING_SECTION> ***************
    echo "<div id='paging'>";

        // ***** for 'first' and 'previous' pages
        if($page>1){
            // ********** show the first page
            echo "<a href='" . $_SERVER['PHP_SELF'] . "' title='Go to the first page.' class='customBtn'>";
                echo "<span style='margin:0 .5em;'> << </span>";
            echo "</a>";
            
            // ********** show the previous page
            $prev_page = $page - 1;
            echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$prev_page}' title='Previous page is {$prev_page}.' class='customBtn'>";
                echo "<span style='margin:0 .5em;'> < </span>";
            echo "</a>";
            
        }
        
        
        // ********** show the number paging
        
        // find out total pages
        $query = "SELECT COUNT(*) as total_rows FROM posts";
        $stmt = $con->prepare( $query );
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $total_rows = $row['total_rows'];
        
        $total_pages = ceil($total_rows / $recordsPerPage);

        // range of num links to show
        $range = 2;

        // display links to 'range of pages' around 'current page'
        $initial_num = $page - $range;
        $condition_limit_num = ($page + $range)  + 1;

        for ($x=$initial_num; $x<$condition_limit_num; $x++) {
            
            // be sure '$x is greater than 0' AND 'less than or equal to the $total_pages'
            if (($x > 0) && ($x <= $total_pages)) {
            
                // current page
                if ($x == $page) {
                    echo "<span class='customBtn' style='background:red;'>$x</span>";
                }
                
                // not current page
                else {
                    echo " <a href='{$_SERVER['PHP_SELF']}?page=$x' class='customBtn'>$x</a> ";
                }
            }
        }
        
        
        // ***** for 'next' and 'last' pages
        if($page<$total_pages){
            // ********** show the next page
            $next_page = $page + 1;
            echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$next_page}' title='Next page is {$next_page}.' class='customBtn'>";
                echo "<span style='margin:0 .5em;'> > </span>";
            echo "</a>";
            
            // ********** show the last page
            echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$total_pages}' title='Last page is {$total_pages}.' class='customBtn'>";
                echo "<span style='margin:0 .5em;'> >> </span>";
            echo "</a>";
        }
        
    echo "</div>";
    
    // ***** allow user to enter page number
    echo "<form action='" . $_SERVER['PHP_SELF'] . "' method='GET'>";
        echo "Go to page: ";
        echo "<input type='text' name='page' size='1' />";
        echo "<input type='submit' value='Go' class='customBtn' />";
    echo "</form>";    
    
    // *************** </PAGING_SECTION> ***************
}

// tell the user if no records were found
else{
    echo "<div class='noneFound'>No records found.</div>";
}
?>

</body>
</html>
Link to comment
Share on other sites

Do you have errors enabled? Note that you can add the following to the top of your script to show all PHP errors:

<?php
//REPORT ALL PHP ERRORS
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
 
 
It seems like the issue is caused by using mysql_* functions like the one here:
$run_posts = mysql_query($get_posts);
 
Based on the earlier query, you didn't connect with mysql_*.
 
 
 
Side note: using the raw value from $_SERVER['PHP_SELF'] opens your script to XSS attacks. More information can be found here:
 
The above article only talks about the <form> tag, but the PHP_SELF variables in your <a> tags are also affected.
Link to comment
Share on other sites

no i dont have any error but here is my mysql connection script

<?php
$host = "localhost";
$db_name = "h2c";
$username = "root";
$password = "";

try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}

//to handle connection error
catch(PDOException $exception){
    echo "Connection error: " . $exception->getMessage();
}
?>

may be it caused because i am using pdo for connection and write mysql here

$run_posts = mysql_query($get_posts);

is that the reason

Edited by hakim
Link to comment
Share on other sites

can it makes errors?

 

When I connect with MySQLi and try to use a mysql_*, I get errors like the following:

 

 

Warning: mysql_query(): No such file or directory in...

 
Warning: mysql_query(): A link to the server could not be established in...

 

 

Since you're using PDO, it should provide similar warnings. Perhaps your server / page is set to hide warnings. Did you add the followings lines to the top of your script?

<?php
//REPORT ALL PHP ERRORS
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
Link to comment
Share on other sites

the php database functions you use must all be from the same library of functions, PDO in this case, to match your database connection code. if the mysql_ functions are not throwing errors, it's likely that your system has set default connection credentials that the mysql_ functions are using to make a connection.

 

next, your code should only have two database queries in it, not three. the first query should get a count of matching rows and the second query retrieves the rows that correspond to the logical page that was requested. the count query should be near the start of the code, not near the end, so that you can limit the logical page number being requested.

 

both of the database queries need the same WHERE clause in them, so that they match the same set of rows (or no WHERE clause if you want to match all the rows.). if there is a $_GET['cat'] value, you need to form the WHERE clause in a php variable and put that php variable into both of the database queries (for the case of no WHERE clause, just initialize the php variable to an empty string and still put it into both queries.)

 

all the pagination links and the form to enter a specific page number need to also propagate any $_GET['cat'] value so that it won't be lost between pages. though, your category search form/links should not propagate the page number (if you select a different category, you would want to default back to page 1.)

 

you are not using prepared queries correctly. a prepared query uses place-holders in the sql statement where data values belong, then you bind the data to the place-holders.

 

edit: lastly, this is more of an organizational point, but it will make writing, testing, and debugging your code easier, with less actual code. you need to separate the php business logic, that determines what to do on the page, from the presentation logic, that outputs the html document. the php business logic would perform initialization, process any post method forms, then do any processing for a get request for the page. the end result of the business logic would be php variables (usually arrays) that the presentation logic would simply test/loop over to output the content on the page. the business logic would contain all the database specific statements and it would contain no html markup. the presentation logic would not contain any database specific statements and it would contain all the html markup.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.