Jump to content

PHP pagination with sessions


Go to solution Solved by requinix,

Recommended Posts

Hello. Can you help me.

Im trying to create table with pagination filtered by date via form. But cant get it to work. Im trying from yesterday. Reading searching but cant understand why is braking.

There are two files:


<!DOCTYPE html>
<html>
  <head>
  <title>Въвеждане на дата</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>   
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <div class = "login-box">
        <p class="headp">Язовир Искър</p>
        <div class = "login">
            <form action = "pagingstatic.php" method = "POST">
                <p>Зареждане на таблица от PostgreSQL по зададена дата.</p>
                <label for="odata">От дата</label>
                <input type = "text" name = "from_date">
                <br />
                <label for="odata">До дата</label>
                <input type = "text" name = "to_date">
                <input type = "submit" name = "submit" value = "Покажи таблица">
            </form>
        </div>
    </div>
  </body>
</html>

And:

<?php
 session_start(); 
    global $limit, $sql, $url, $pagesize, $pagecount, $absolutepage, $recordcount;  



    $_SESSION['from_date'] = $_POST['from_date'];
    $_SESSION['to_date'] = $_POST['to_date'];


    // Configuration...  
    $db = pg_Connect("dbname=Test user=postgres password=1111");
$errordate = "";
$noerror = "";
if (!$db)
{
    die('Error: Could not connect: ' . pg_last_error());
}

// If current page number, use it 
// if not, set one! 


if(!isset($_GET['page'])){ 
$page = 1; 
} else { 
$page = $_GET['page']; 
} 

$_SESSION['page'] = $page;

// Define the number of results per page 
$max_results = 4; 

// Figure out the limit for the query based 
// on the current page number. 
$from = (($page * $max_results) - $max_results); 

// Perform MySQL query on only the current page number's results 
$from_date = $_SESSION['from_date'];
$to_date = $_SESSION['to_date'];
$result = pg_query($db, "SELECT * FROM import.mock_data WHERE date BETWEEN '$from_date' AND '$to_date' ORDER by date LIMIT $max_results OFFSET $from "); //LIMIT $pagesize OFFSET $offset


$i = 0;
echo '<!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" href="style.css"></head><body><div class="table_box"><table><tr>';
while ($i < pg_num_fields($result))
{
    $fieldName = pg_field_name($result, $i);
    echo '<td>' . $fieldName . '</td>';
    $i = $i + 1;
}
echo '</tr>';
$i = 0;
while ($row = pg_fetch_row($result)) 
{
    echo '<tr>';
    $count = count($row);
    $y = 0;
    while ($y < $count)
    {
        $c_row = current($row);
        echo '<td>' . $c_row . '</td>';
        next($row);
        $y = $y + 1;
    }
    echo '</tr>';
    $i = $i + 1;
}
pg_free_result($result);

// Figure out the total number of results in DB: 

// $total_results = pg_result(pg_query("SELECT COUNT(*) as Num FROM import.mock_data WHERE date BETWEEN '" . $_SESSION['from_date'] . "' AND '" . $_SESSION['to_date'] . "'"),0); 
$total_results = pg_result(pg_query("SELECT COUNT(*) as Num FROM import.mock_data WHERE date BETWEEN '$from_date' AND '$to_date'"),0); 

// Figure out the total number of pages. Always round up using ceil() 
$total_pages = ceil($total_results / $max_results); 

// end table
echo '</table>';

// Build Page Number Hyperlinks 
echo "<br /><center>Изберете страница<br />"; 

// Build Previous Link 
if($page > 1){ 
$prev = ($page - 1); 
echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$prev\"><<Предишна</a> "; 
} 

for($i = 1; $i <= $total_pages; $i++){ 
if(($page) == $i){ 
echo "$i "; 
} else { 
echo "<a href=\"".$_SERVER['PHP_SELF']."?page=$i\">$i</a> "; 
} 
} 

// Build Next Link 
if($page < $total_pages){ 
$next = ($page + 1); 
echo '<a href="'.$_SERVER['PHP_SELF'].'?page=$next">Следваща>></a>'; 
} 
echo '<br />от ' .$_SESSION['from_date']. ' до ' .$_SESSION['to_date']. '</center>';
echo '</div></body></html>';
pg_close($db);
?>

Some guys help me by wrote me:

$_POST['from_date'] and $_POST['to_date'] only exists when you post the form the first time. Next page uses GET without those, but you're still trying to get them from the $_POST array. When fetching data, use the GET method only. Then you can populate the pagination links with the same filters. –

 

and:

 

 

Your form method is post but you are using $_GET. You won't get the values.

 

After that edited my code. But again still have errors. Can you explain me how to do it with example. Please :)

Link to comment
https://forums.phpfreaks.com/topic/304410-php-pagination-with-sessions/
Share on other sites

Whatever you edited was not what those two people were telling you to do.

 

Use GET for the form and $_GET in your code.

 

You also have to fix your links. As an example,

echo "<a href=\"".htmlspecialchars($_SERVER['PHP_SELF']."&page=$prev")."\"><<Предишна</a> "; 
//                ^ add that                             ^ change that

Ok. :) I edited the Get in form and in the code before that. Only the links was the same. After your advise i did this:

<?php 
session_start();
    global $limit, $sql, $url, $pagesize, $pagecount, $absolutepage, $recordcount;  
    // Configuration...  
$db = pg_Connect("dbname=Test user=postgres password=1111");
$_SESSION['from_date'] = $_GET['from_date'];
$_SESSION['to_date'] = $_GET['to_date'];
//$from_date = $_GET['from_date'];
//$to_date = $_GET['to_date'];
if (!$db)
{
	die('Error: Could not connect: ' . pg_last_error());
}

// If current page number, use it 
// if not, set one! 


if(!isset($_GET['page'])){ 
$page = 1; 
} else { 
$page = $_GET['page']; 
} 


// Define the number of results per page 
$max_results = 2; 

// Figure out the limit for the query based 
// on the current page number. 
$from = (($page * $max_results) - $max_results); 

// Perform MySQL query on only the current page number's results 
$from_date = $_SESSION['from_date'];
$to_date = $_SESSION['to_date'];
$result = pg_query($db, "SELECT * FROM import.mock_data WHERE date BETWEEN '$from_date' AND '$to_date' ORDER by date DESC LIMIT $max_results OFFSET $from "); //LIMIT $pagesize OFFSET $offset


$i = 0;
echo '<!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" href="style.css"></head><body><div class="table_box">Период от ' .$_SESSION['from_date']. ' до ' .$_SESSION['to_date']. '<br /><a href="test_table.php" class="button">Промени дата</a><table><tr>';
while ($i < pg_num_fields($result))
{
	$fieldName = pg_field_name($result, $i);
	echo '<td>' . $fieldName . '</td>';
	$i = $i + 1;
}
echo '</tr>';
$i = 0;
while ($row = pg_fetch_row($result)) 
{
	echo '<tr>';
	$count = count($row);
	$y = 0;
	while ($y < $count)
	{
		$c_row = current($row);
		echo '<td>' . $c_row . '</td>';
		next($row);
		$y = $y + 1;
	}
	echo '</tr>';
	$i = $i + 1;
}
pg_free_result($result);

// Figure out the total number of results in DB: 

// $total_results = pg_result(pg_query("SELECT COUNT(*) as Num FROM import.mock_data WHERE date BETWEEN '" . $_SESSION['from_date'] . "' AND '" . $_SESSION['to_date'] . "'"),0); 
$total_results = pg_result(pg_query("SELECT COUNT(*) as Num FROM import.mock_data WHERE date BETWEEN '$from_date' AND '$to_date'"),0); 

// Figure out the total number of pages. Always round up using ceil() 
$total_pages = ceil($total_results / $max_results); 

// end table
echo '</table>';

// Build Page Number Hyperlinks 
echo "<br /><center>Изберете страница<br />"; 

// Build Previous Link 
if($page > 1){ 
$prev = ($page - 1); 
echo "<a href=\"".htmlspecialchars($_SERVER['PHP_SELF']."&page=$prev")."\"><<Предишна</a> "; 
} 
for($i = 1; $i <= $total_pages; $i++){ 
if(($page) == $i){ 
echo "$i "; 
} else { 
echo "<a href=\"".htmlspecialchars($_SERVER['PHP_SELF']."&page=$i")."\">$i</a> "; 
} 
} 

// Build Next Link 
if($page < $total_pages){ 
$next = ($page + 1); 
echo "<a href=\"".htmlspecialchars($_SERVER['PHP_SELF']."&page=$next")."\">Следваща ⇨</a>"; 
} 
echo '</div></body></html>';
pg_close($db);
?>

but after pressing on paginate link i get this:

Not Found

The requested URL /pagingstatic.php&page=2 was not found on this server.

I forgot to paste the error cod from the first post:

Notice: Undefined index: from_date in C:\WEB\Apache24\htdocs\pagingstatic.php on line 6

Notice: Undefined index: to_date in C:\WEB\Apache24\htdocs\pagingstatic.php on line 7

Warning: pg_query(): Query failed: ERROR: invalid input syntax for type date: "" LINE 1: SELECT * FROM import.mock_data WHERE date BETWEEN '' AND '' ... ^ in C:\WEB\Apache24\htdocs\pagingstatic.php on line 36

Warning: pg_num_fields() expects parameter 1 to be resource, boolean given in C:\WEB\Apache24\htdocs\pagingstatic.php on line 41

Warning: pg_fetch_row() expects parameter 1 to be resource, boolean given in C:\WEB\Apache24\htdocs\pagingstatic.php on line 49

Warning: pg_free_result() expects parameter 1 to be resource, boolean given in C:\WEB\Apache24\htdocs\pagingstatic.php on line 64

Warning: pg_query(): Query failed: ERROR: invalid input syntax for type date: "" LINE 1: ...*) as Num FROM import.mock_data WHERE date BETWEEN '' AND '' ^ in C:\WEB\Apache24\htdocs\pagingstatic.php on line 69

Warning: pg_result() expects parameter 1 to be resource, boolean given in C:\WEB\Apache24\htdocs\pagingstatic.php on line 69

Edited by xfire123
  • Solution

Eh, I should stop being lazy.

 

Create an array to track the variables you want to pass between pages. That's the from_date and to_date.

$qs = array(
	"from_date" => $_GET["from_date"],
	"to_date" => $_GET["to_date"]
);
When you want a link, use /pagingstatic.php with http_build_query($qs). When you want a page number too, use array_merge with $qs and the page number.

$prev = ($page - 1);
$link = "/pagingstatic.php?" . http_build_query(array_merge($qs, array("page" => $prev)));
echo "<a href=\"".htmlspecialchars($link)."\"><<Предишна</a> ";

Eh, I should stop being lazy.

 

Create an array to track the variables you want to pass between pages. That's the from_date and to_date.

$qs = array(
	"from_date" => $_GET["from_date"],
	"to_date" => $_GET["to_date"]
);
When you want a link, use /pagingstatic.php with http_build_query($qs). When you want a page number too, use array_merge with $qs and the page number.

$prev = ($page - 1);
$link = "/pagingstatic.php?" . http_build_query(array_merge($qs, array("page" => $prev)));
echo "<a href=\"".htmlspecialchars($link)."\"><<Предишна</a> ";

What sorcery is this? ;) You are gold! Thank you very much.

I'm trying for 2 days to fix it but i cant. Need to read more...

Can i still post a questions like this in future? Of Course after i make a hard work to solve it alone of course.

 

 

After this, there is no issues :)

// Build Previous Link 
if($page > 1){ 
$prev = ($page - 1);
$link = "/pagingstatic.php?" . http_build_query(array_merge($qs, array("page" => $prev)));
echo "<a href=\"".htmlspecialchars($link)."\"><<Предишна</a> ";
} 

for($i = 1; $i <= $total_pages; $i++){ 
if(($page) == $i){ 
echo "$i "; 
} else { 
$link2 = "/pagingstatic.php?" . http_build_query(array_merge($qs, array("page" => $i)));
echo "<a href=\"".htmlspecialchars($link2)."\">$i</a> ";
} 
} 

// Build Next Link 
if($page < $total_pages){ 
$next = ($page + 1); 
$link3 = "/pagingstatic.php?" . http_build_query(array_merge($qs, array("page" => $next)));
echo "<a href=\"".htmlspecialchars($link3)."\">Следваща ⇨</a> ";
}  
Edited by xfire123

What sorcery is this? ;)

The key is http_build_query: it takes an array of keys and values and pieces them together for you to use in a URL's query string. The array_merge() combines the page number with the array when you need it included.

 

Can i still post a questions like this in future?

Of course!
  • Like 1
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.