Jump to content

can somebody explain what this for loop does? please...


co.ador

Recommended Posts

<?php 
$range=4;
// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {

   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) { 
         // 'highlight' it but don't make a link
         echo " [<b >$x</b>] ";
      // if not current page...
  
      }

  else {
         // make it a link http_build_query( $strName,$strZipCode, $strState, $arrFoodTypes, $arrOfferings)
         echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x&strZipCode= ". $strZipCode . "'>$x</a> ";
      } // end else
   
   } // end if 

} 
?>

Link to comment
Share on other sites

It's just to show the pages around the current page number (if they exist). The range is the padding. For example, if you are on page 2 it will loop from -2 to 6, omitting -2, -1 and 0 as they aren't valid page numbers, then echoing out

1 2 3 4 5 6 (assuming up to page 6 exists)

Link to comment
Share on other sites

if you notice in the link that I have added a variable called

&strZipCode= ". $strZipCode . "'

 

If passes ok when click on page two but when clicked in page 3 then it passes empty as

 

http//indexpagination.php?currentpage=3&strZipCode=

 

I don't understand if the for loop has anything to do with it..

 

 

Help please

 

Link to comment
Share on other sites

<?php
//Extract the variable from the url
$strZipCode = isset($_REQUEST['frmSearch']['zipcode'])?mysql_real_escape_string($_REQUEST['frmSearch']['zipcode']):'';

// check weather $strZipCode is not empty else $_GET the variable from the pagination link strZipCode 
if(!empty($strZipCode)){
  $query4 = "SELECT state, zip, county
FROM restaurants 
WHERE 
(zip= '$strZipCode')"; 
echo $query4;
$result = mysql_query($query4);
$arrstate = mysql_fetch_array($result);
echo '<div class="information"><label>County:</label>
        <div>'. $arrstate['county']. '</div>
  <label>State:</label>
             <div>'. $arrstate['state']. '</div>
	   <label>Zip Code:</label>
             <div>'. $arrstate['zip']. '</div></div> <br><br>';
		 }
		 else {
		 $query4 = "SELECT state, zip, county
FROM restaurants 
WHERE 
zip= ".  $_GET['strZipCode']. ""; 
echo $query4;
$result = mysql_query($query4);
$arrstate = mysql_fetch_array($result);
echo '<div class="information"><label>County:</label>
        <div>'. $arrstate['county']. '</div>
  <label>State:</label>
             <div>'. $arrstate['state']. '</div>
	   <label>Zip Code:</label>
             <div>'. $arrstate['zip']. '</div></div> <br><br>';

		 }
//pagination script 
$sql = "SELECT COUNT(*) FROM restaurants";
$result = mysql_query($sql) or trigger_error(mysql_error());
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 6;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
} else {
   // default page num
   $currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db 
$sql = "SELECT zip, state, address FROM restaurants LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);

// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
   // echo data
   echo $list['zip'] . " : " . $list['state'] . "<br />";
} // end while

/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
  echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1&strZipCode= ". $strZipCode. "'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage&strZipCode= ". $strZipCode . "'><</a> ";
} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
       echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x&strZipCode= ". $strZipCode . "'>$x</a> ";
      } // end else
   } // end if 
} // end for
                 
// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
  echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage&strZipCode= ". $strZipCode . "'>></a> ";
   // echo forward link for lastpage
   echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages&strZipCode= ". $strZipCode . "'>>></a> ";
} // end if


?>

 

Why in the third page of the pagination script the

strZipCode
appended variable is passing empty

 

This is the link passing empty variable after the second page. Page one and two pass the variable but the url in the third doesn't contain the variable value,

echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x&strZipCode= ". $strZipCode . "'>$x</a> ";

 

help please

Link to comment
Share on other sites

just loops through the pages i beleive im not one for prying but i think ur code needs some work, i mean its all crowded andd the functionality of it is questionable. i wasnt even able to feel like i wanted THAT SCRIPT on my website

 

Well I'm sure your code's just tip top.

 

...

 

Anyway, I can't see any reason for it to not display on the third page; by that do you mean that you're unable to click on to the third page, or that you can actually access the third page fine but it would be the links to the fourth page that don't display correctly? Is this across all links?

Link to comment
Share on other sites

Excuse me MrAdam is the link to the third that doesn't pass the variable any ways.

 

there is a another part of the code I haven't place because I thought that was not part of the problem.

 

which is

<?php 
$arrSQLFilters = array();
    
    // whether or not zip codes table needs to be included
    $boolIncludeZipCodes = false;

    // Zipcode filter
    if(!empty($strZipCode)) {
        $boolIncludeZipCodes = true;
    
        $arrSQLFilters[] = sprintf(
            "r.zip LIKE '%s'"
            ,"%$strZipCode%"
        );
    }
    
    // State filter
    if(!empty($strState)) {
        $boolIncludeZipCodes = true;
    
        $arrSQLFilters[] = sprintf(
            "r.state = '%s'"
            ,$strState
        );

    }

    // Restaurants name filter
    if(!empty($strName)) {
        $arrSQLFilters[] = sprintf(
            "r.restaurantname LIKE '%s'"
            ,"%$strName%"
        );
    }

    // Food types filter
    if(!empty($arrFoodTypes) && !empty($arrFoodTypes[0])) {
    $arrSQLFilters[] = sprintf(
          'r.restaurants_id IN
               (SELECT
                     restaurants_id
                  FROM
                     restaurants_restaurant_food_types
                 WHERE
                     restaurants_food_types_id IN (%s)
                 GROUP
                    BY
                     restaurants_id
                HAVING 
                     COUNT(*) = %u)'
            ,/*mysql_real_escape_string(*/ implode(',',$arrFoodTypes) /*)*/
            ,count($arrFoodTypes)
        );
    }

    // Offerings Filter ie. eat-in, lunch, dinner, etc
    if(!empty($arrOfferings)) {
      $arrSQLFilters[] = sprintf(
          'r.restaurants_id IN
               (SELECT
                     restaurants_id 
                 FROM
                     restaurants_to_restaurant_offering
		     
                 WHERE
                     restaurants_offerings_id IN (%s)
                 GROUP
                    BY
                     restaurants_id
                HAVING 
                     COUNT(*) = %u)'
            ,/*mysql_real_escape_string(*/ implode(',',$arrOfferings) /*)*/
            ,count($arrOfferings) );
     }

// get the info from the db 

$strSQL = sprintf(
    'SELECT
         r.restaurants_id
        ,r.restaurantname
        ,r.image
        ,r.description
        ,r.address
        ,r.zip
        ,r.state
    FROM
        restaurants r
        %s
        %s
        %s
        LIMIT %d, %d'
    ,$boolIncludeZipCodes === true?'INNER JOIN restaurants_to_zip_codes rz ON r.restaurants_id = rz.restaurants_id ':''
    ,empty($arrSQLFilters)?'':' WHERE '.implode(' AND ',$arrSQLFilters)   
    ,$boolIncludeZipCodes === true?'GROUP BY r.restaurants_id':''
    ,$offset, $rowsperpage
);
$arrResult = mysql_query($strSQL) or die("Cannot execute:". mysql_error());

    while($arrRow = mysql_fetch_assoc($arrResult)) {
        $arrRestaurants[] = $arrRow;
    
}

$i = 1;
foreach($arrRestaurants as $arrRestaurant) {

  echo "<div class=\"shoeinfo1\">
   <img src=\"images/spacer.gif\" alt=\"spacer\" class=\"spacer2\" />
      <h2 class=\"infohead\">". $arrRestaurant['restaurantname'] . "</h2>
      <div class=\"pic\"><img class=\"line\" src= ". $arrRestaurant['image'] ." alt=\"picture\" width=\"100%\" height=\"100%\" /></div>

      <h5> Rating:</h5><h4>";


	$ratingData = Rating::OutputRating($arrRestaurant['restaurantname']);
      
      if (Error::HasErrors())
      {
        echo Error::ShowErrorMessages();
        Error::ClearErrors();
      }
      else
      {
        echo $ratingData;
      }  
  echo"</h4> 
    	<h3>Description:</h3>
    	<div id=\"description\"><p>".$arrRestaurant['description']." </p></div> 
	<div class=\"suabe2\">Address:<span class=\"suabe\">".$arrRestaurant['address']."</span></div>
	<div id=\"state\">State:<span class=\"suabe\">". $arrRestaurant['state']. "</span></div>
       <h6>Zip:<span class=\"suabe\">". $arrRestaurant['zip'] . "</span></h6>
<p><a href=\"#\">More</a></p></div>

";
$i++; 
if ($i > 1 && $i % 4 == 0 ) 
{
  echo "<div class=\"clearer\"></div>";

}
}?>

And it goes in place of the second query in the pagiination link the above code sustitude this query and while loop

[code]<?php
$sql = "SELECT zip, state, address FROM restaurants LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {   
// echo data  
echo $list['zip'] . " : " . $list['state'] . "<br />";} 
?>

 

The whole code...

 

?>[/code]

 

 

<?php
//Extract the variable from the url
    $strName = isset($_REQUEST['frmSearch']['name'])?mysql_real_escape_string($_REQUEST['frmSearch']['name']):'';
    $strZipCode = isset($_REQUEST['frmSearch']['zipcode'])?mysql_real_escape_string($_REQUEST['frmSearch']['zipcode']):'';
    $strState = $_REQUEST['frmSearch']['state']/*)*/;
    $arrFoodTypes = isset($_REQUEST['frmSearch']['food_types'])?mysql_real_escape_string($_REQUEST['frmSearch']['food_types']):array();
    $arrOfferings = isset($_REQUEST['frmSearch']['offerings'])?mysql_real_escape_string($_REQUEST['frmSearch']['offerings']):array();

// check weather $strZipCode is not empty else $_GET the variable from the pagination link strZipCode 
if(!empty($strZipCode)){
  $query4 = "SELECT state, zip, county
FROM restaurants 
WHERE 
(zip= '$strZipCode')"; 
echo $query4;
$result = mysql_query($query4);
$arrstate = mysql_fetch_array($result);
echo '<div class="information"><label>County:</label>
        <div>'. $arrstate['county']. '</div>
  <label>State:</label>
             <div>'. $arrstate['state']. '</div>
	   <label>Zip Code:</label>
             <div>'. $arrstate['zip']. '</div></div> <br><br>';
		 }
		 else {
		 $query4 = "SELECT state, zip, county
FROM restaurants 
WHERE 
zip= ".  $_GET['strZipCode']. ""; 
echo $query4;
$result = mysql_query($query4);
$arrstate = mysql_fetch_array($result);
echo '<div class="information"><label>County:</label>
        <div>'. $arrstate['county']. '</div>
  <label>State:</label>
             <div>'. $arrstate['state']. '</div>
	   <label>Zip Code:</label>
             <div>'. $arrstate['zip']. '</div></div> <br><br>';

		 }
//pagination script 
$sql = "SELECT COUNT(*) FROM restaurants";
$result = mysql_query($sql) or trigger_error(mysql_error());
$r = mysql_fetch_row($result);
$numrows = $r[0];

// number of rows to show per page
$rowsperpage = 6;
// find out total pages
$totalpages = ceil($numrows / $rowsperpage);

// get the current page or set a default
if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) {
   // cast var as int
   $currentpage = (int) $_GET['currentpage'];
} else {
   // default page num
   $currentpage = 1;
} // end if

// if current page is greater than total pages...
if ($currentpage > $totalpages) {
   // set current page to last page
   $currentpage = $totalpages;
} // end if
// if current page is less than first page...
if ($currentpage < 1) {
   // set current page to first page
   $currentpage = 1;
} // end if

// the offset of the list, based on current page 
$offset = ($currentpage - 1) * $rowsperpage;
// get the info from the db 
$arrSQLFilters = array();
    
    // whether or not zip codes table needs to be included
    $boolIncludeZipCodes = false;

    // Zipcode filter
    if(!empty($strZipCode)) {
        $boolIncludeZipCodes = true;
    
        $arrSQLFilters[] = sprintf(
            "r.zip LIKE '%s'"
            ,"%$strZipCode%"
        );
    }
    
    // State filter
    if(!empty($strState)) {
        $boolIncludeZipCodes = true;
    
        $arrSQLFilters[] = sprintf(
            "r.state = '%s'"
            ,$strState
        );

    }

    // Restaurants name filter
    if(!empty($strName)) {
        $arrSQLFilters[] = sprintf(
            "r.restaurantname LIKE '%s'"
            ,"%$strName%"
        );
    }

    // Food types filter
    if(!empty($arrFoodTypes) && !empty($arrFoodTypes[0])) {
    $arrSQLFilters[] = sprintf(
          'r.restaurants_id IN
               (SELECT
                     restaurants_id
                  FROM
                     restaurants_restaurant_food_types
                 WHERE
                     restaurants_food_types_id IN (%s)
                 GROUP
                    BY
                     restaurants_id
                HAVING 
                     COUNT(*) = %u)'
            ,/*mysql_real_escape_string(*/ implode(',',$arrFoodTypes) /*)*/
            ,count($arrFoodTypes)
        );
    }

    // Offerings Filter ie. eat-in, lunch, dinner, etc
    if(!empty($arrOfferings)) {
      $arrSQLFilters[] = sprintf(
          'r.restaurants_id IN
               (SELECT
                     restaurants_id 
                 FROM
                     restaurants_to_restaurant_offering
		     
                 WHERE
                     restaurants_offerings_id IN (%s)
                 GROUP
                    BY
                     restaurants_id
                HAVING 
                     COUNT(*) = %u)'
            ,/*mysql_real_escape_string(*/ implode(',',$arrOfferings) /*)*/
            ,count($arrOfferings) );
     }

// get the info from the db 

$strSQL = sprintf(
    'SELECT
         r.restaurants_id
        ,r.restaurantname
        ,r.image
        ,r.description
        ,r.address
        ,r.zip
        ,r.state
    FROM
        restaurants r
        %s
        %s
        %s
        LIMIT %d, %d'
    ,$boolIncludeZipCodes === true?'INNER JOIN restaurants_to_zip_codes rz ON r.restaurants_id = rz.restaurants_id ':''
    ,empty($arrSQLFilters)?'':' WHERE '.implode(' AND ',$arrSQLFilters)   
    ,$boolIncludeZipCodes === true?'GROUP BY r.restaurants_id':''
    ,$offset, $rowsperpage
);
$arrResult = mysql_query($strSQL) or die("Cannot execute:". mysql_error());

    while($arrRow = mysql_fetch_assoc($arrResult)) {
        $arrRestaurants[] = $arrRow;
    
}

$i = 1;
foreach($arrRestaurants as $arrRestaurant) {

  echo "<div class=\"shoeinfo1\">
   <img src=\"images/spacer.gif\" alt=\"spacer\" class=\"spacer2\" />
      <h2 class=\"infohead\">". $arrRestaurant['restaurantname'] . "</h2>
      <div class=\"pic\"><img class=\"line\" src= ". $arrRestaurant['image'] ." alt=\"picture\" width=\"100%\" height=\"100%\" /></div>

      <h5> Rating:</h5><h4>";


	$ratingData = Rating::OutputRating($arrRestaurant['restaurantname']);
      
      if (Error::HasErrors())
      {
        echo Error::ShowErrorMessages();
        Error::ClearErrors();
      }
      else
      {
        echo $ratingData;
      }  
  echo"</h4> 
    	<h3>Description:</h3>
    	<div id=\"description\"><p>".$arrRestaurant['description']." </p></div> 
	<div class=\"suabe2\">Address:<span class=\"suabe\">".$arrRestaurant['address']."</span></div>
	<div id=\"state\">State:<span class=\"suabe\">". $arrRestaurant['state']. "</span></div>
       <h6>Zip:<span class=\"suabe\">". $arrRestaurant['zip'] . "</span></h6>
<p><a href=\"#\">More</a></p></div>

";
$i++; 
if ($i > 1 && $i % 4 == 0 ) 
{
  echo "<div class=\"clearer\"></div>";

}
}?>/******  build the pagination links ******/
// range of num links to show
$range = 3;

// if not on page 1, don't show back links
if ($currentpage > 1) {
   // show << link to go back to page 1
  echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1&strZipCode= ". $strZipCode. "'><<</a> ";
   // get previous page num
   $prevpage = $currentpage - 1;
   // show < link to go back to 1 page
   echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage&strZipCode= ". $strZipCode . "'><</a> ";
} // end if 

// loop to show links to range of pages around current page
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
   // if it's a valid page number...
   if (($x > 0) && ($x <= $totalpages)) {
      // if we're on current page...
      if ($x == $currentpage) {
         // 'highlight' it but don't make a link
         echo " [<b>$x</b>] ";
      // if not current page...
      } else {
         // make it a link
       echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x&strZipCode= ". $strZipCode . "'>$x</a> ";
      } // end else
   } // end if 
} // end for
                 
// if not on last page, show forward and last page links        
if ($currentpage != $totalpages) {
   // get next page
   $nextpage = $currentpage + 1;
    // echo forward link for next page 
  echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage&strZipCode= ". $strZipCode . "'>></a> ";
   // echo forward link for lastpage
   echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages&strZipCode= ". $strZipCode . "'>>></a> ";
} // end if


?>

 

Why in the third page of the pagination script the

strZipCode
appended variable is passing empty

 

This is the link passing empty variable after the second page. Page one and two pass the variable but the url in the third doesn't contain the variable value,

echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x&strZipCode= ". $strZipCode . "'>$x</a> ";

 

help please

 

Link to comment
Share on other sites

Ahh, of course.

 

$strZipCode = isset($_REQUEST['frmSearch']['zipcode'])?mysql_real_escape_string($_REQUEST['frmSearch']['zipcode']):'';

 

When you're passing the "strZipCode" through to the second page you've given it a different parameter name:

 

echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage&strZipCode= ". $strZipCode . "'>></a> ";

Link to comment
Share on other sites

Ahh, of course.

 

$strZipCode = isset($_REQUEST['frmSearch']['zipcode'])?mysql_real_escape_string($_REQUEST['frmSearch']['zipcode']):'';

 

When you're passing the "strZipCode" through to the second page you've given it a different parameter name:

 

echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage&strZipCode= ". $strZipCode . "'>></a> ";

 

that one. way off

Link to comment
Share on other sites

Sure. When the user submits the search originally, you're selecting the zip code with:

 

$strZipCode = isset($_REQUEST['frmSearch']['zipcode'])?mysql_real_escape_string($_REQUEST['frmSearch']['zipcode']):'';

 

However when you're passing the variable back through the URL you naming it "strZipCode":

 

echo  " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage&strZipCode= ". $strZipCode . "'>></a> ";

 

Which would obviously be returned with $_GET['strZipeCode'] or $_REQUEST['strZipCode']. So the first set of links are being populated correctly, however when you reach the second page the links to third page are broken because a blank is returned [from first piece of code].

Link to comment
Share on other sites

<?php
if (!empty ($strZipCode)){
$strZipCodes = $strZipCode;
}
else
{
$strZipCodes = $_REQUEST['strZipCode']; 
}
?>

 

 

The above code solved the problem. I have change the variable name to $strZipCodes and put equal to the one coming from the form and has two variable with different names but the same value...

 

Thank you MrAdam and all of you guys.

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.