Page 1 of 1

Pagination seems to conflict with data display.

Posted: Thu Jun 23, 2011 4:29 pm
by drayarms
I must begin by apologizing for the lengthiness of this posting but I really couldn't edit it to be any shorter. Hopefully one of you reading this is quite familiar with both PHP pagination, and displaying search results in rows. Well here's what I'm trying to do. I created a page that displays results from a simple search query. the results displayed are the pictures of a users of a website, alongside their usernames. I'm trying to display the results in rows of 4, as dictated by the $items variable on line 27 of the script i will post below in a minute. Well, the script works just fine as intended. Then when I add the blocks of code that should paginate the results (the pagination blocks of code are indented to the left of the script), I run into a bunch of problems. First of all, oddly enough, when I set the number of rows to be displayed per page to any number order than 4, the page never completes the loading process and the pagination links are not displayed. The page only loads fully and displays the pagination links when $numrows is set to 4 and even then, when I click on the link to take me to the next page, no results get displayed. Instead I get the "No results match this search query' message which is displayed when the query returns no results. It seems to me like there are problems with the pagination code, I'm not quite sure. I have tried about 3 different pagination codes which I found from online tutorials and they all present the same problems. Any help? Here is my page.

PS One more problem, when I set the $limit variable(which sets the number of results displayed per row) to 4, the data to be displayed(pictures) get extra padding between them, pushing the last one out of the page. Ironically as explained above, this is the only case where the page loads completely and the pagination links get displayed. To make you picture this easier, I have removed the authentication restrcition off this page and I'll provide the link for you to see what I'm talking about http://mygeneric.info/search_results.ph ... city=white

Code: Select all

<?php

//address error handling

ini_set ('display_errors', 1);
error_reporting (E_ALL & ~E_NOTICE);


//authenticate user
require('auth.php');


//Set session timeout
require('inactive.php');



//Set the page title before the header file
$title = 'Search Results';


//Get variables from previous page, profile_searh.php
$ethnicity = $_GET['ethnicity'];


//Items to display per row.
$items = 4;

require ('header.php'); //need the header





echo'			<div id="content" class="">



				<div id="left_content" class="">



					



				</div> <!--closes left content-->

					



				<div id="right_content" class="">

					<div id= "right_content_inner_border">       ';



						
							//Obtain the required page number from the $_GET array. Note that if it is not present it will default to 1.


if (isset($_GET['pageno'])) {
   $pageno = $_GET['pageno'];
} else {
   $pageno = 1;
} // if



							// Connect to the database.

        						require_once ('config.php');

							//Count how many rows will satisfy the current query..

							$query = "SELECT* FROM members INNER JOIN images ON members.member_id = images.member_id WHERE members.ethnicity = '$ethnicity' AND images.image_cartegory = 'main'  ";

 							$result = mysql_query($query);


$numrows = mysql_num_rows($result);


//Use the values in $rows_per_page and $numrows in order to identify the number of the last page.

$rows_per_page = 4;

$lastpage      = ceil($numrows/$rows_per_page); 


//Check that the value of $pageno is an integer between 1 and $lastpage.

$pageno = (int)$pageno;

if ($pageno > $lastpage) {

   $pageno = $lastpage;

} // if

if ($pageno < 1) {

   $pageno = 1;

} // if


//Construct the LIMIT clause for the sql SELECT statement.

$limit = 'LIMIT ' .($pageno - 1) * $rows_per_page .',' .$rows_per_page;


//Now we can issue the database qery and process the result.

$query = "SELECT* FROM members INNER JOIN images ON members.member_id = images.member_id WHERE members.ethnicity = '$ethnicity' AND images.image_cartegory = 'main' $limit ";

$result = mysql_query($query) or die(mysql_error());

							//Check for success here.

							if(!$result)

							{

    								die('<p>Could not retrieve the data because: <b>' . mysql_error(). '</p>');

    								// Handle as desired

							}else{  //If query is valid.

    								if(mysql_num_rows($result) > 0){

									//Start a table to contain the results.

									echo '<table border= "0" width="100%" cellspacing= "1" cellpadding ="1" align ="center"> ';

									//Need a counter.

									$i = 0;

									
									//Retrieve each record.

       			 						while ($row = mysql_fetch_assoc($result)){ 

										//Do we need to start a new row?

										if($i == 0) {echo "<tr>\n";}


									//Print the record


									echo"\t<td align=\"center\"> 
						

									<div id='search_pic_wrap'>
									<div id='no_photo'>";


									//Define variables to be passed via url.

									$friend= $row['member_id'];

								
			 						//Make sure an uploaded photo is present.  if ($row['image'] !== NULL) {

									echo"<a href='friend.php?friend=$friend' >";

 

                    	 						// Note that we are building our src string using the filename from the database.

                     	 						echo "<img src=\"images/" . $row['image'] . "\" width=\"140\" maxheight=\"154\" />";    

                   

                    	 						echo "</a>";   


			 						echo"<h2 style= 'position:relative;bottom:25px;'>" .$row['username']. "</h2>


							
									//End of if there is an uploaded pic.} 
									</div> <!--closes no photo-->
									</div> <!--closes search pic wrap-->

									</td>\n";


									//Icrement the counter.

									$i++;

										//Do we need to end the row?

										if ($i == $items) {echo "</tr>\n";
													$i = 0; //Reset counter.
										}


									
			 						}//End of while loop.


									if ($i > 0) {//Last row was incomplete.


										//Print the necessary number of cells.

										for ($i < $items; $i++;) { echo "<td>&nbsp;</td>\n";
										}

										//Complete the row.

										echo '</tr>';

									}//End of if $i is greater than 0

									//Close the table.

									echo '</table>';


echo '<div style= " position:absolute;top:1050px;left:600px;">';

//Construct the hyperlinks which will allow the user to select other pages. We will start with the links for any previous pages.

if ($pageno == 1) {

   echo " FIRST PREV ";

} else {

   echo " <a href='{$_SERVER['PHP_SELF']}?pageno=1'>FIRST</a> ";

   $prevpage = $pageno-1;

   echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$prevpage'>PREV</a> ";

} // if


//Inform the user of his current position in the sequence of available pages.
        		 
echo " ( Page $pageno of $lastpage ) ";

//Provide the links for any following pages.

if ($pageno == $lastpage) {

   echo " NEXT LAST ";

} else {

   $nextpage = $pageno+1;

   echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$nextpage'>NEXT</a> ";

   echo " <a href='{$_SERVER['PHP_SELF']}?pageno=$lastpage'>LAST</a> ";

} // if	

echo'</div>';



   		 						}else {//No rows returned. End of if number of rows is greater than 0 loop.

        
        								echo 'No results match this search query.' ;

    									}

							}//End of else if query is valid.

						



echo'						

					</div> <!--closes right content inner border-->	


			

					
				</div> <!--closes right content-->


			

			</div> <!--closes content-->      ';









require ('footer.php'); //need the footer


?>
 
 

Re: Pagination seems to conflict with data display.

Posted: Fri Jun 24, 2011 12:46 am
by social_experiment
pagination+script
This script might give you some guidance as to your dilemma.

Re: Pagination seems to conflict with data display.

Posted: Fri Jun 24, 2011 3:40 am
by Idri
After having looked through your code I noticed a few things.

Let's start as to why your code will freeze up when you use a number other than 4 (or a multiple of 4 for that matter).

Code: Select all

//Print the necessary number of cells.
for ($i < $items; $i++;) { 
	echo "<td>&nbsp;</td>\n";
}
Above code will result in an infinite loop. When explained in words, the condition of the loop would equate to roughly this; $i is smaller than $items and increment $i as long as [missing, thus infinitely].

Now as to why you're not getting any results after clicking on your pagination link. Notice the URL (or the parameters at least) you provided,
?ethnicity=white
after clicking on one of the links, you'll get sent to a page with only
?pageno=1
Notice something missing? You'll have to pass the ethnicity parameter to the anchor elements you use for your pagination.
?pageno=1&ethnicity=white
The issue with the padding resides in the stylesheet you've made. Specifically, search_pic_wrap has a left of 55px. If you set that to 0 it will shift back to its normal position.

Lastly, your query is currently susceptible to SQL injection. I'd advise you to use the mysql_real_escape_string function (PHP.net - Mysql Real Escape String) to sanitize any form of user-generated input.

Edit:

I knew I forgot something. I'm not sure how your database tables are built, nor do I know what fields are mandatory so this could be a non-issue for you.
In your query you have the following (I'll leave out the irrelevant bits)

Code: Select all

$query = "SELECT* FROM members INNER JOIN images ON members.member_id = images.member_id <snip>"
When using an inner join you'll have to keep in mind that the member_id value must be present or the row will not be in your resultset.
If your goal is to retrieve members without an image then you´ll have to use a Left join. For when using a left join, you will get the row in your resultset, albeit with NULL values where the join didn't meet the specified conditions.
Mysql.com - Reference Manual: Joins

Re: Pagination seems to conflict with data display.

Posted: Mon Jun 27, 2011 3:16 am
by drayarms
@ idri, thanks for the insights. i had already resolved some the issues (the padding problem, and the results not showing up in subsequent pages )but was at a loss about why the page didn't finish loading till i read your thread. It makes sense what you suggested about the infinite loop, I'll take a look at it, but first to you have any suggestions as to how i can close the loop? Also as for the inner join, I used that precisely because I wanted to include columns from both the members and images tables in my results. The results are displayed perfectly just as i want them to be(If you like I can give u a link to the current page and temporarily de-authenticate it for you to see). The only issue left is the infinite loop.

Re: Pagination seems to conflict with data display.

Posted: Mon Jun 27, 2011 6:56 am
by social_experiment

Code: Select all

 for ($i < $items; $i++;) 
// give $i a starting point
 for ($i = 0; $i < $items; $i++;)
Have you tried giving $i a value inside the for loop

Re: Pagination seems to conflict with data display.

Posted: Mon Jun 27, 2011 3:21 pm
by drayarms
I had a suggestion from another site, I didn't quite understand the authur's explanation but he was saying something about each of the 3 parts of the for loop being optional, and since no initial expression had to be evaluated, the loop had to begin with a semicolon. So he advised me to change the for loop to

for (;$i = 0; $i < $items; $i++)

and amazingly, that worked. But I still didn't get why.

Re: Pagination seems to conflict with data display.

Posted: Tue Jun 28, 2011 12:00 pm
by social_experiment

Code: Select all

<?php
for ($i = 1; ; $i++) {
    if ($i > 10) {
        break;
    }
    echo $i;
}
?>
The example you gave looks a bit strange. According to the manual if you leave an expression out you add a semi-colon. Your example makes it look like the loop had 4 arguments. The example i pasted is from the php manual shows the syntax of a for statement with only 2 expressions.