Ok... I have another problem. I have tryed to split the resultts of my query in to multiple pages with a fixed number of results per page... I used this tutorial for it:

http://www.php-mysql-tutorial.com/php-mysql-paging.php

Originally, my page worked as follows:

There was a search frame where the user would select different things through dropdown lists or checkboxes... hisselections were sent via a post method as parameters to the "display" page.

On the display page those parameters were obtained through the "$_request" or "$_post" methodes and asigned to local variables wich were then used as conditions in the query.

Now, AFTER I implemented the tutorial everything works perfectly... except one thing.

Well, let me start from the beginning:

In the new versione the parameters are still beying sent from the browse frame to the display frame via request or post and then used locally in the query string. the tutorial also implemented a limit parameter to the query determining the first page and the number of results per page.

The results are split acordingly and the corect number of pages is displayed. It also echoes next, previous and page number links for accessing the other results of the query.

well... these links look something like this:

$page = $pageNum + 1;
 $next = " <a href=\"$self?page=$page\">[Next]</a> ";

this basicly tells the page to reload itself and send the new $page variable to the reloadedpage.

When the page reloads there's an if statement at the very top that verifies if the page has been reloaded and has resived a page number:

if(isset($_GET['page']))
{
    $pageNum = $_GET['page'];
}

$offset = ($pageNum - 1) * $rowsPerPage;

so after the page reloads it will use the new offset variable in the "limit" parameter of the query.

THE PROBLEM IS that when the page reloads all the requested variables from the browse frame are lost and the query will load everything in the database ( just as if there are no conditions set ). Even if I forciblly RE-execute the REQUEST lines to get the variables from the browse frame, the variables just return empty... even though the conditions are still set on the browse frame...

SO my question is... is there no way to send the requestev variables from the browse frame to the reloaded page like we sent the page number?

SOmething like this:

$next = " <a href=\"$self?page=$page?cond1=$cond1?cond2=$cond2...?condx=$condx\">[Next]</a> ";

and then on the page reload check it would be like this?

if(isset($_GET['page']))
{
    $pageNum = $_GET['page'];
    $cond1=$_GET['cond1'];
    $cond2=$_GET['cond2'];
    ...
    $condx=$_GET['condx'];
}

Or if there's any other way to transmit multyple variables to a new page... Or maybe just send the WHOLE query string with all the parameters already included as it was executed when the search button was clicked... like this:

$next = " <a href=\"$self?page=$page?sqlstring=$sqlstring\">[Next]</a> ";

and at the page reload check it owuld be like this:

if(isset($_GET['page']))
{
    $pageNum = $_GET['page'];
    $sqlstring=$_GET['sqlstring'];
}

Please help...

Recommended Answers

All 19 Replies

Member Avatar for Rhyan

Marcmm,

Normally the sql statement should be re-run every time with the new parameters. This is why it is good to use $_GET, instead of $_POST, because $_GET does not explicitly require a form and fields to be submitted.
What you actually need to do is always check the $_GET variables as if it is the first time you run the code.

If you want you may also check this thread
http://www.daniweb.com/forums/thread156953.html

Marcmm,

Normally the sql statement should be re-run every time with the new parameters. This is why it is good to use $_GET, instead of $_POST, because $_GET does not explicitly require a form and fields to be submitted.
What you actually need to do is always check the $_GET variables as if it is the first time you run the code.

If you want you may also check this thread
http://www.daniweb.com/forums/thread156953.html

SO when you said to use "get" in stead of "post"... were you refearign to when I submit the search parameters from the browse frame:

ECHO "<FORM NAME=hoteluri METHOD=post ACTION=display.php TARGET=result>";
...
code for several dropdown lists and checkboxes (and maybe even a textbox in the future);
...
ECHO "</FRAME>";

should I use get method when submitting these results and loading the display frame?

Or were you refearing to the way I'm requesting these results from within the display frame:

$combo_1 = $_REQUEST['combo_1 from browse frame'];
$combo_2 = $_REQUEST['combo_2 from browse frame'];

the above is requesting the variable transmited by the dropdown lists ( and to my understanding $_request is like "post" and "get" combined anyways )

Or

IF ( ISSET($_POST[checkboxname]) )
	{
	$sql_query .= "AND ( condition )";
	}

to check if the checkboxes on the browse frame have been checked.

And yes, the sql statement IS rerun everytime you click a next or previus page... but I loose all my parameters when I do so ( bolth the variables from the dropdown lists and the checkbox checks... for some reason, hen I reload the display frame, the page no longer seems to execute these lines of code... either it no longer recognises the browse frame... or it just skips all the checks... I jsut know that when the page is reloaded all the conditions are gone and the query loads everything from the database )... I need to be able to memorise those parameters in order to rebuild the exact same query when I click next or previous...

Member Avatar for Rhyan

Yes, by usign get i refer to defining your search form as mehtod=get.

This is how normally get works. You can see the get request as all the symbols in the browser address which appear like this pagename.php?variable=smth&another=whatever

Using the get method can be simulated using links, which are not actual get request, but are equally valid for the server. In short <a href='pagename.php?variable=smth&another=whatever'>My link</a> is interpreted by the server absolutely the same way as e.g. when you press the submit button in your form where method=get.

I hope the above makes sense for you and you easily can figure out how to create your page number links. But, to make sure it is clear, here is an example for you.

1. Imagine you have 5 pages mentioned at the bottom of the page like numbers

1|2|3|4|5

each number should be wrapped by a link tag <a></a>
so the href attribute of your <a> for number one should look something like

<a href='target_page.php?page=1&param1=value1&param2=&value2>1</a>

In order to achieve that, you need to check the GET method on each load of your page as we have discussed earlier using if (isset($_GET...))
This time however, instead of only creating your sql statement using .='and ....', your if(isset... cycle should look something like this.

if(isset($_GET['param1']))
  {
  $param1 = $_GET['param1'];
  $SQL .= 'AND whatever='.$param1;
  $pagelink .= '&param1='$param1;
  }

So, at the end you will have to echo this code for each page number

for($i=0;$i<$page_numbers;$i++)
  {
  echo '<a href="yourpage.php?page='.$i.$pagelink.'">'.$i.'</a>';
  }

Hope it is clear now.

Rhyan answered this the same time as I did. His post pretty much says the same thing.

you need to send the searched string in the url with each pagination link (what you are doing is called pagination, just thought I would let you know). Do NOT send your query in the url. That is a HUGE security risk.

You can also use sessions, but in this case I think you'd be better off send the string in the url.

also, make sure you are using $_GET and not $_REQUEST as it is not very secure.

Ok... so I redefined my search button form and now it reads like this:

ECHO "<FORM NAME=hoteluri METHOD=get ACTION=display.php TARGET=result>";

ok... now on to the if ifset statement...

right now it looks like this:

if(isset($_GET['page']))
{
    $pageNum = $_GET['page'];
}


$offset = ($pageNum - 1) * $rowsPerPage;

If I understand corectly... I have to have all the code to rebuild the query inside this if statement... ( or a, I even more confuse and this is another if ifset statement different from the one that apears at the very top of the page )

Or do I have one of these if isset statements for each variable I transmit via the next/previous/number links?

Or is this just one single if isset statement wich coveres all the necesary variables needed to build the query... if so how do you handle the fact that the number of parameters needed varies ( acording to what the user selects from the browse frame )

it's a bit confusing... sorry...

if(isset($_GET['param1']))
  {
  $param1 = $_GET['param1'];
  $SQL .= 'AND whatever='.$param1;
  $pagelink .= '&param1='$param1;
  }

I'm guessing that my param 1 you are refearing to one of the variables needed to create the query... like for example one of the variables depicting the selection in a dropdown list on the browse frame.
Well if so... that means I have to copy paste the entire query building process inside this if statement... unfortunatelly that will be a lot of code since the code to build it contains multiple if statements reflecting the combinations betwen the different posible combinations of the drop down lists ( checking if they have anything but the default option selected ).

I also am having troulbe understanding this line:

$pagelink .= '&param1='$param1;

what dose that do?

at present my display area for the first/last and page number links looks like this:

( I calculate the numrows variable by executing the query separatelly without the limit parameter to figure out how many lines it would have in total, then I use it to determine how many pages would contain the query results.

$maxPage = ceil($numrows/$rowsPerPage);

$self = $_SERVER['PHP_SELF'];
$nav  = '';

	for($page = 1; $page <= $maxPage; $page++)
	{

   	if ($page == $pageNum)
   		{
   	   	$nav .= " $page "; // no need to create a link to current page
  	 	}
  	else
  		{
  		$nav .= " <a style=' text-decoration: none;' href=\"$self?page=$page\">$page</a> ";
   		}

	}

if ($pageNum > 1)
{
   $page  = $pageNum - 1;
   $prev  = " <a style=' text-decoration: none;' href=\"$self?page=$page\">[Prev]</a> ";

   $first = " <a style=' text-decoration: none;' href=\"$self?page=1\">[First Page]</a> ";
}
else
{
   $prev  = '&nbsp;'; // we're on page one, don't print previous link
   $first = '&nbsp;'; // nor the first page link
}

if ($pageNum < $maxPage)
{
   $page = $pageNum + 1;
   $next = " <a href=\"$self?page=$page\">[Next]</a> ";

   $last = " <a href=\"$self?page=$maxPage\">[Last Page]</a> ";
}
else
{
   $next = '&nbsp;'; // we're on the last page, don't print next link
   $last = '&nbsp;'; // nor the last page link
}

I'm affraid this get VS post debate is overpowering me it seems...

Ok, I figured out the logic behind your earlyer post... but one question still remains...

it's easy for the dropdown list parameters since they wiull always exist... having either 0 or a value different then 0 to transmit... so those parameters would be present for every link every time reguardless of the circumstances...

but what happenes with the checkboxes? if the user dosen't select a checkbox... that parameter shouldn't exist... what do I do then?

and about the parameter list to transmit... is it viable to just keep adding parameters to it via .= so that they would be like this:

<a href='target_page.php?page=1&param1=value1&param2=&value2>1</a>

is that a viable construction? just adding ?name=$name over and over ( with different parameters of course ) will be recognised as multyple parameters and then I check each of them in the if issetstatement with an independent if isset statement for each of them?

Member Avatar for Rhyan

Well,

we have to start it all over again obvioursly :)

The things go like this.

In order to retrieve results from a search query, you have to do the following

1. Check what get or post variables have been submitted. In your case - only GET variables.
2. If a get value is set and is valid, you include it in your SELECT statement using .= and....
3. Send a request to the mysql and retrieve all records corresponding to defined select statement.
4. Display your results.

Now, because you have too many results to display you want to extend your capabilities by making multiple pages using pagination function

We should go like this
1. Check what get or post variables have been submitted. In your case - only GET variables.
2. If a get value is set and is valid, you include it in your SELECT statement using .= and....
a) Check If isset current page. If current page is not set default it to 0, otherwise current page value is equal to submitted get value. In both cases(either set or not set in the get method) include the LIMIT clause to the end of your SELECT statement.
b) During checking of your GET variables, apart from the select statement, create new string that will be used by the page numbering scheme only. Name it something like - $page_number_link_string. This string will carry the get values you want to store when you click on next page number.
3. Send a request to your sql server in order to retrieve the results. Note that the LIMIT option in your sql will not return the complete number of records that match the SELECT statement, but only a number of records <= limited record number. SO, in order to make the page numbering correctly, you have to run a hidden SELECT statement WITHOUT LIMIT parameter and store the value of total returned records in a variable - e.g. $total_records_in_db.
4. Display the limited number of records retrtieved.
5. Create the pagination below your displayed records in the following way.
a) Calculate page numbers related to total record number
a1. If total records / records to be displayed = any integer, total page numbers = total records / records to be displayed
a2. if total records / records to be displayed = float, total page numbers = (total records / records to be displayed)+1 - this will give you the extra page for those records that are less than the maximum records to be presented on a page.
b) display the page numbers you have calculated in the following way.
b1. for($i=0; $i< page numbers; $i++) echo your page number as a link, as i have explained in my previous post.


And that's it.

I hope you get the logic. I cannot do more for you but create the whole page for you, but you'll never learn like that....

Member Avatar for Rhyan

Ok, I figured out the logic behind your earlyer post... but one question still remains...

it's easy for the dropdown list parameters since they wiull always exist... having either 0 or a value different then 0 to transmit... so those parameters would be present for every link every time reguardless of the circumstances...

but what happenes with the checkboxes? if the user dosen't select a checkbox... that parameter shouldn't exist... what do I do then?

and about the parameter list to transmit... is it viable to just keep adding parameters to it via .= so that they would be like this:

<a href='target_page.php?page=1&param1=value1&param2=&value2>1</a>

is that a viable construction? just adding ?name=$name over and over ( with different parameters of course ) will be recognised as multyple parameters and then I check each of them in the if issetstatement with an independent if isset statement for each of them?

Well, is it viable - 100%, because otherwise your SQL select will be different and you will present different results when you click on a page number.

What concerns the checkboxes - I did not get your question. But i think that you want to ask me if the user changes some or all of the parameters on the search form, what will happen then with the links and with the results. If this is your question then, note the following.

I intentionally mentioned that the a href=?param... is a simulated get request. This link represents a dummy get request, but it is simulated. You will get the very same results by just changing the numbers in your browser's address field and by hitting enter
However, if you fill the form and hit the submit button, then new values will be provided via the get method. In this way your page numbers will automatically reflect the new changed parameters and your link will be different.

I hope I said this clear, because even I got confused :D

Ok... after reading the above I realised how unnecesarelly I complicated myself with the code... SO I deleted most of it and started from scratch this is how the beginning of the document looks like right now ( this is before starting to implement the split paging )

$sql_line="SELECT DISTINCT tables.names
		        FROM tables
			WHERE ((standard cond1)
			AND (standard cond2)"; 

$sql_end=") 
	  ORDER BY something ASC";

IF ( ISSET($_GET[combo_1]) )
	{
	$combo_1 = $_GET['combo_1'];
		IF ( $combo_1 <> 0 ) // check to see if user has selected something other then the default
			{
			$sql_line .= "AND (cond1)";
			}
	}

IF ( ISSET($_GET[combo_2]) )
	{
	$combo_2 = $_GET['combo_2'];
		IF ( $combo_2 <> 0 ) // check to see if user has selected something other then the default
			{
			$sql_line .= "AND (cond2)";
			}
	}

IF ( ISSET($_GET[checkbox1]) )
	{
	$sql_line .= "AND ( cond3 )";
	}

IF ( ISSET($_GET[checkbox2]) )
	{
	$sql_line .= "AND ( cond4 )";
	}

IF ( ISSET($_GET[checkbox3]) )
	{
	$sql_line .= "AND ( cond5 )";
	}

$sql_line .= $sql_end;   // I atatch the end of the sql line

this format ctually simplifyed my coding on the display page considerably... so thanks for the hint... basicly now... each time the page loads it will suposedly check to see weather any of those parameters have been sent to the page... by default they are sent by the browse frame... and next they will be sent by the page links... am I corect?

Member Avatar for Rhyan

Yes, you are correct.

One suggestion only

this code

IF ( ISSET($_GET[combo_2]) )
	{
	$combo_2 = $_GET['combo_2'];
		IF ( $combo_2 <> 0 ) // check to see if user has selected something other then the default
			{
			$sql_line .= "AND (cond2)";
			}
	}

you can change it like this and it will be valid.

IF ( ISSET($_GET[combo_2]) && $_GET[combo_2]!=0 )
	{
	$combo_2 = $_GET['combo_2'];
	$sql_line .= "AND (cond2)";
	}

oh... nevermind... I understand what you mean... ok... I will change it... then get started on the split pages...

Ok... more progress:

$currentpage = 0; // I had to set the current page var to 0 outside the if isset loop because the else branch there dosen't seem to work

$sql_line="SELECT DISTINCT tables.names
		        FROM tables
			WHERE ((standard cond 1 )
			AND (standard cond 2 )";

$sql_end=") 
	  ORDER BY something ASC";

$sql_limit=" LIMIT $currentpage,5"; // I made the first value of the limit to point to the currentpage and the second representing how many results to display per page... 5 at the moment...

IF ( ISSET($_GET[page]) )
	{
	$currentpage = $_GET['page'];
	}
ELSE
	{
	$currentpage = 0; // this branch dosen't work... but I supose it makes sence... the page is beying sent even by default from the browse frame...
	}

IF ( ISSET($_GET[combo_1]) && $_GET[combo_1]!=0 )
	{
	$combo_1 = $_GET['combo_1'];
	$sql_line .= "AND (cond 1)";
	$pagelink .= "&combo_1 = $combo_1";
	}

IF ( ISSET($_GET[combo_2]) && $_GET[combo_2]!=0 )
	{
	$combo_2 = $_GET['combo_2'];
	$sql_line .= "AND (cond 2)";
	$pagelink .= "&combo_2 = $combo_2";
	}

IF ( ISSET($_GET[checkbox1]) )
	{
	$sql_line .= "AND ( cond3 )";
	$pagelink .= "&checkbox1 = AND ( cond3 )";	
	}

IF ( ISSET($_GET[checkbox2]) )
	{
	$sql_line .= "AND ( cond4 )";
	$pagelink .= "&checkbox2 = AND ( cond4 )";	
	}

IF ( ISSET($_GET[checkbox3]) )
	{
	$sql_line .= "AND ( cond5 )";
	$pagelink .= "&checkbox3 = AND ( cond5 )";	
	}

$sql_line .= $sql_end; // I add the order part

$sql_totallines = $sql_line; // I create the string for the hidden query

$rez_totallines = mysql_query($sql_totallines) OR DIE (mysql_error()); // execute the hidden querry

$total_lines = mysql_num_rows($rez_totallines); // count the total number of rows the query will have.

$sql_hoteluridisp .= $sql_limit; // atatch the limit parameter

$rez_hoteluridisp = mysql_query($sql_hoteluridisp) OR DIE (mysql_error()); // execute the real query

$linii_hoteluridisp=mysql_num_rows($rez_hoteluridisp); // count the number of results in the new query

Is it ok so far?

Member Avatar for Rhyan

Yes, it is ok like that... Keep on

Unfortunatelly it still dosen't work... and the page calculation system is flawed...

here's what I have in adition to the above:

$pagination = $total_lines/$displaylines; // ( total_lines is the variable I obtained when I did the hidden query to determine how many records my query would have without the limit parameter / display lines is a var that hoalds the number of results per page wich defaults to 5 at the begining of the page. )

	IF ( is_int ( $pagination ) )
		{
		$total_pages = $pagination;
		}

	IF ( is_float ( $pagination ) )
		{
		$total_pages = $pagination + 1;
		}

	FOR ($i=0; $i<$total_pages; $i++)
		{
		ECHO "<a href='display.php?page=$i$pagelink'> $i </a>";
		}

well first of all the page count is always wrong... at present my DB hoalds just 6 entries... if just hit search and not select anything ( meaning that I want to display all the records ) the division should be 5 records on first page and 1 record on a second page...

the calculation should be:

$pagination=6/5=1.2; // that's float so it should take this route:

IF ( is_float ( $pagination ) )
		{
		$total_pages = $pagination + 1=2.2; ( is there no way to just take the integer part of a number? not rounding it )
		}

the code will display 3 pages... namelly 0 1 and 2... and their code dose not work either...

when I seelct either of them I will either loose all or part of the atributes contained in the $pagelink string. and the same page loads with the same results...basicly I still loose the parameters allong the way and even if some of the parameters do make it through the reload they don't seem to work...

this is how the link to one of the pages looks like if I rightclick on it:

mydomain/display.php?page=1&combo_1%20=%201 ( this is suposing I changed the first dropdown list and selected something other then the default from it ).

Now suposedly when It reloads the page it's suposed to do this:

IF ( ISSET($_GET[combo_1]) && $_GET[combo_1]!=0 ) ( bolth are suposed to be true since I selected option 1 from the list so it should be set AND different from 0 )
	{
	$combo_1 = $_GET['combo_1']; // suposed to give the passed variable back to the original var. dosen't seem to happen.
	$sql_line= "AND (localitate.ID = $combo_localitatedisp)"; // same as above... it's not executed.
	$pagelink .= "&combo_localitatedisp = $combo_localitatedisp"; // this either...
	}

so on the new page there's no parameters and the page loads all the results reguardless of what I had selected originally...

EDIT: I just checked... the IF statement is not even executed when I reload the page... the if isset dosen't recognise that I'm sending parameters via the reload link and just skips theentire tree. the problem must lie in the transmited string $pagelink!

I experiance a similar problem with the checkboxes... if I have all the checkboxes selected when I click on a new page I'll loose all but one of the checkbox parameters and that one that persists is never used and the page will still load all the records ( well it will still be limited to that wich is written in the limit parameter as the current page... )

What am I doing wrong?

I've noticed that the link seems to have certain problems sending the combo parameters...

they are under this form:

&combo1='number'

but the link will only say &combo1=

seems as though it has problems reading ' characters or something...

Wich means either it transmits an empty parameter to the reloaded page... or it dosen't transmit anything... reguardless... on the next page the if isset structures are not executed ( well except for the page if isset tree... that one works ).

Member Avatar for Rhyan

Sorry, my bad - use % instead of / for division of total numbers against display numbers. I don't know exactly in English how this division is called, but the result is integer with remaining result that is indivisible. That is the result will be 6%5=1 and remaining 1 record to be displayed on page 2.

Now, about your checkboxes. As I mentioned earlier - if you check some checkboxes, you need to hit the submit button, not the next page number. The next page number will execute the same search query as your previous search, without modification. In order to change your query params you have to use your search form and the submit button.

it still dosen't work...

6%5

and going through this:

IF ( is_float ( $pagination ) )
		{
		$total_pages = $pagination + 1;
		}

still gives 3 pages instead of 2...

And I STILL loose all my parameters when I click any of the page links... so when the page reloads and reexecutes the query it dosen't have the parameters and what happenes is that it ends up executing the query with no parameters...

the problem has to be in the transmit line:

ECHO "<a href='display.php?page=$i$pagelink'> $i </a>";

cause up untill there the strings are all fine... but once I hit any of those links... I losoe all my parameters... namelly everything contained inthe &pagelink variable...

are you sure that it's the "&" symbol that ties multyple variables to be sent with the ? symbol from page to page?

Ok... I belive I fixed it... It seems to work properly now... my errore seems to have steemed from the fact that I had a few variables in highercase in some areas... and sicne var names are casesensitive... it pushed the entire system overboard...

Gona do some testing to make sure everythign works then I'll post my solution ( if nothing else comes up ).

Well I tested it and it works... so problem solved... thanks for the input guys... using the get methode and implementing the posting and retrieving of data from page to page was something I doubt I would have figured out on my own...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.