Jump to content

Can You Echo A $Var That Is Defined Later On In The Script?


icthos

Recommended Posts

Can you echo a $var that is defined later on in the script?

 

Ive got a good grasp of PHP basics but Im struggling in building a control structure that addresses this problem. I am making a web application that can be simplified to this:

 

<?php

include('functions.php');

include('head.php');

include('body.php');

?>

 

functions.php connects to the database etc, but for ease of explanation it is just this:

 

<?php $pageNumber = 6; ?>

 

head.php contains basic HTML head code with a dynamic stylesheet loader

 

<!doctype html>

<html>

<head>

<link rel="stylesheet" href="<?php echo $stylesheet; ?>.css" type="text/css">

</head>

 

body.php contains basic body template code, and gets its actual contents from another file

 

<body>

<div class="wrapper">

<?php include($pageNumber.".php"); ?>

</div>

</body>

</html>

 

And then as we are on page 6, page 6 contains:

 

<?php

$stylesheet = "yellow";

?>

<p>This is page six! You will notice that page six is coloured yellow, unlike any of the other pages</p>

 

I need to be able to control which stylesheet loads at the level of this page. I could put the stylesheet inclusion code after the include($pageNumber) part but then it wouldnt validate. Is there any way I can make it look futher on in the code for the value of $stylesheet if it isnt defined yet? Or is there a better control structure?

Link to comment
Share on other sites

No, you cannot do that. It's like you trying to predict what's on the next page of a book without reading it. :) You would have to come up with a different structure. Off the top of my head, you would either have to store this information in a file/database so that you can read it at the top, or you would probably have to use classes. For instance, many frameworks allow you to add items to the head of the rendered HTML from the view class. I haven't exactly done anything like this myself, though. The first option is by far the easiest, but also the less flexible one.

Link to comment
Share on other sites

// styles.php
$stylesheets = array(1 => 'red', 'green', 'blue', 'black', 'purple', 'yellow');

<?php
include('functions.php');
include('styles.php');
include('head.php');
include('body.php');
?>

<?php $pageNumber = 6; ?>

<!doctype html>
<html>
<head>
<link rel="stylesheet" href="<?php echo $stylesheets[$pageNumber]; ?>.css" type="text/css">
</head>

<p>This is page six! You will notice that page six is coloured yellow, unlike any of the other pages</p>

Link to comment
Share on other sites

Also you could try a cookie or session

 

That's true, and we can add globals to the list as well. However, those are poor solutions. :) For a small project, I would store an array in a file like Andy-H does in his example. For bigger projects, I would store it in a database and cache it on the web server. For large projects, I would do neither and look into using a framework.

Link to comment
Share on other sites

That's true, and we can add globals to the list as well. However, those are poor solutions. :) For a small project, I would store an array in a file like Andy-H does in his example. For bigger projects, I would store it in a database and cache it on the web server. For large projects, I would do neither and look into using a framework.

 

Using global is never a valid solution.

Edited by AyKay47
Link to comment
Share on other sites

Short answer - programming does not involve magic or the ability to go back in time. You cannot use a variable until after it has been assigned a value.

 

You are trying to paste together a html document using php include statements for the various sections. That method is inflexible and limited in what it can do.

 

A solution would be to form your dynamic output in php variables, then at the end of your code, produce the actual html document and echo the various php variables at the appropriate place in the html document. The following is an example of a pagination script that shows this method -

 

<?php
$title = "Pagination w/css links";
// settings used by this code -
$rows_per_page = 20; // how many rows to display per logical page
$pagination_name = 'pageno'; // the $_GET[xxxxx] index name to use for pagination
$pagination_range = 3; //  maximum number of pagination links to show either side of the currently selected page

// connect to your database server and select your database here...

// assuming this is being used for a search script, output a simple search form and produce a $where_clause to match the rows you are interested in
$search_form = "<form method='get' action=''>Search: <input type='text' name='search'><input type='submit'></form>";

// get and condition any search term
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$where_clause = '';
if($search != ''){
   // form a simple LIKE '%search term%' comparison
   $where_clause = sprintf("WHERE name LIKE '%s%%'",mysql_real_escape_string($search));
}

// define the main and count queries
$main_query = "SELECT * FROM collages $where_clause";
$count_query = "SELECT COUNT(*) FROM collages $where_clause";

// find the total number of matching rows
$result = mysql_query($count_query) or die("Query failed: $count_query<br />Error: " . mysql_error());
list($total_rows) = mysql_fetch_row($result);

// calculate the total number of logical pages
$total_pages = ceil($total_rows/$rows_per_page);

// get and condition or set a default for the requested page
$requested_page = isset($_GET[$pagination_name]) ? intval($_GET[$pagination_name]) : 1;

// set max/min limits for the requested page. max first, then min so if the total is zero (no matching data), the requested page is 1
if($requested_page > $total_pages){
  $requested_page = $total_pages;
}
if($requested_page < 1){
  $requested_page = 1;
}

// calculate the starting row number for the requested logical page
$offset = ($requested_page - 1) * $rows_per_page;

// form the actual query to retrieve the matching data for the requested logical page
$query = "$main_query LIMIT $offset, $rows_per_page";

// query for the actual data
$result = mysql_query($query) or die("Query failed: $query<br />Error: " . mysql_error());

// get number of rows returned by the query for the logical page
$num_rows = mysql_num_rows($result);
$main_content = '';
if($num_rows == 0){
   // query matched no rows
   $main_content .= "There are no matching records to display on this page.";
} else {
   $main_content .= "Your query matched $total_rows record" .($total_rows > 1 ? 's' : '').". ";
   $main_content .= "Displaying records: ".($offset+1)." - " . ($offset+$num_rows) . ".<br />";
   // loop over the matching rows and output the data the way you want on your page
   while($row = mysql_fetch_assoc($result)){
       $main_content .= $row['name'] . '<br />';
   }
}

// build pagination navigation links (if there's more than one page)
// this code uses http_build_query to build the query string on the end of the URL so that any existing get parameters, such as a search term, are not modified. This code only modifies the pagination get parameter and leaves all other get parameters as is.
$pagination_links = ''; // build pagination links in a string (output it later in your actual content on the page)
if($total_pages > 1){
   // produce 'first' and 'prev' links
   // <li><a href="#" class="prevnext disablelink">« previous</a></li>
   // <li><a href="#" class="prevnext">« previous</a></li>
   if($requested_page > 1){
       // 'first' page link
       $_GET[$pagination_name] = 1; // set/replace the pagination GET parameter (all other GET parameters unchanged)
       $pagination_links .= "<li><a class='prevnext' href='?" . http_build_query($_GET, '', '&') . "'><<</a></li> ";
       // 'prev' page link
       $_GET[$pagination_name] = $requested_page - 1; // set/replace the pagination GET parameter (all other GET parameters unchanged)
       $pagination_links .= "<li><a class='prevnext' href='?" . http_build_query($_GET, '', '&') . "'><</a></li> ";
   } else {
       // text only place holders
       $pagination_links .= "<li><a href='#' class='prevnext disablelink'><<</a></li> ";
       $pagination_links .= "<li><a href='#' class='prevnext disablelink'><</a></li> ";
   }

   // loop to produce links for a range of pages around the currently selected page
   for($x = $requested_page - $pagination_range; $x < $requested_page + $pagination_range + 1; $x++){
       // if between min and max page number
       if($x > 0 && $x <= $total_pages){
           // if currently requested page, output text only place holder
           if($x == $requested_page){
               //<li><a href="#" class="currentpage">1</a></li>
               $pagination_links .= "<li><a href='#' class='currentpage'>$x</a></li> ";
           } else {
               // output page link
               $_GET[$pagination_name] = $x; // set/replace the pagination GET parameter (all other GET parameters unchanged)
               $pagination_links .= "<li><a href='?" . http_build_query($_GET, '', '&') . "'>$x</a></li> ";
           }
       }
   }

   // produce 'next' and 'last' links
   if($requested_page != $total_pages){
       // 'next' page link
       $_GET[$pagination_name] = $requested_page + 1; // set/replace the pagination GET parameter (all other GET parameters unchanged)
       $pagination_links .= "<li><a class='prevnext' href='?" . http_build_query($_GET, '', '&') . "'>></a></li> ";
       // 'last' page link
       $_GET[$pagination_name] = $total_pages; // set/replace the pagination GET parameter (all other GET parameters unchanged)
       $pagination_links .= "<li><a class='prevnext' href='?" . http_build_query($_GET, '', '&') . "'>>></a></li>";
   } else {
       // text only place holders
       $pagination_links .= "<li><a href='#' class='prevnext disablelink'>></a></li> ";
       $pagination_links .= "<li><a href='#' class='prevnext disablelink'>>></a></li>";
   }
}
?>
<html>
<head>
<title><?php echo $title; ?></title>
<style type="text/css">

.pagination{
padding: 2px;
}

.pagination ul{
margin: 0;
padding: 0;
text-align: left; /*Set to "right" to right align pagination */
font-size: 16px;
}

.pagination li{
list-style-type: none;
display: inline;
padding-bottom: 1px;
}

.pagination a, .pagination a:visited{
padding: 0 5px;
border: 1px solid #9aafe5;
text-decoration: none;
color: #2e6ab1;
}

.pagination a:hover, .pagination a:active{
border: 1px solid #2b66a5;
color: #000;
background-color: #FFFF80;
}

.pagination a.currentpage{
background-color: #2e6ab1;
color: #FFF !important;
border-color: #2b66a5;
font-weight: bold;
cursor: default;
}

.pagination a.disablelink, .pagination a.disablelink:hover{
background-color: white;
cursor: default;
color: #929292;
border-color: #929292;
font-weight: normal !important;
}

.pagination a.prevnext{
font-weight: bold;
}

</style>
<body>
<div><?php echo $search_form; ?></div>
<div class="pagination">
   <ul>
       <?php echo $pagination_links; // echo the links wherever you want in the content on your page ?>
   </ul>
</div>
<div><?php echo $main_content; ?></div>
</body>
</html>

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.