Solved

Dynically Include Variables from another page

Posted on 2014-09-23
8
113 Views
Last Modified: 2014-09-25
I have a Web page document that I am building Dynamically, depending on where you are in the country.  The document is very long and has different parts depending on where you are in the country.  I have between 10 -20 different sub documents to include in the main document depending on where you are located.

I want to keep all of the sub-documents in another file and turn each sub-document into a variable.  So in my sub-documents.php page I have
<?php
$ks = 'BLAHH BLAH BLAH';

$ny = 'BLAHH BLAH BLAH';

$tx = 'BLAHH BLAH BLAH';
etc...
?>

Open in new window


In my main document page I want to have:
<?php
include('sub-documents.php');

if($state == 'Kansas') {
$state = $ks(from sub-document page)
}
if($state == 'New York{
$state = $ny(from sub-document page)
}
if($state == 'Texas') {
$state = $tx(from sub-document page)
}

$html ='Hello and welcome.  I see you are from '.$state.'";

Open in new window

How do I make the variable within the sub-documents.php page available for use in the documents.php page
0
Comment
Question by:rgranlund
  • 5
  • 3
8 Comments
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40339864
It will be in the same scope and namespace that was in effect at the time of the include() function call.  You may want to change the values for those variables so you can illustrate the process in way that gives meaningful results.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40339896
This man page describes the process.
http://php.net/manual/en/function.include.php

Here's an example.  First, the "sub" script that gets brought in via include()
<?php // demo/temp_rgranlund_sub.php
error_reporting(E_ALL);
$abc = 'ABC';
$xyz = 'XYZ';

Open in new window

Next, the script that uses the include() statement.
<?php // demo/temp_rgranlund_main.php
error_reporting(E_ALL);

if (empty($abc)) echo "<br>ABC IS EMPTY BEFORE THE INCLUDE() STATEMENT";

// ASSIGN A VARIABLE
$xyz = "<br>THIS IS THE ORIGINAL XYZ - IT WILL GET OVERWRITTEN BY THE VARIABLE IN THE INCLUDE()";
echo $xyz;

// BRING IN A SCRIPT
include('temp_rgranlund_sub.php');

echo "<br>$abc $xyz";

Open in new window

0
 
LVL 7

Author Comment

by:rgranlund
ID: 40340003
When I do this part:
// BRING IN A SCRIPT
include('temp_rgranlund_sub.php');

echo "<br>$abc $xyz";

I get the warning: Notice: Undefined variable: abc
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40340014
Please post the EXACT scripts as you have them now.  Also, it may seem like it's a small thing, but a Notice in PHP is not the same as a Warning.  These are terms of art and have different meanings.
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 7

Author Comment

by:rgranlund
ID: 40340110
sub-document.php
<?php
$toca = '<div style="page-break-before:always;"></div>
A.	It is hereby agreed that for purposes of the coverage provided by this endorsement, SECTION I – COVERAGES is amended to include the following:  
ROADSIDE ASSISTANCE <br /><br />
Coverage<br /><br />
If a covered loss occurs, we will provide and pay for ground transportation for you and the insured bicycle and one (1) guest from the point of loss to any destination within 50 miles from the point of the covered loss.  We will only pay for your cost of ground transportation three (3) times in one policy year.    
What We Pay <br /><br />
We will pay for all charges for ground transportation through the use of StarrCYCLE/SPOKE Roadside Assistance for you and the insured bicycle and one (1) guest from the point of loss to any destination within 50 miles from the point of the covered loss.  
If for any reason we are not able to arrange service through StarrCYCLE/SPOKE Roadside Assistance, we will reimburse you for ground transportation for an amount not to exceed $50. 
No deductible will apply to the coverage provided by this endorsement. <br /><br />
Exclusions<br /><br />
We will not pay for the cost of ground transportation: <br /><br /> 
1.	outside of the United States of America;<br /><br />
2.	to any destination greater than 50 miles from the point of loss; and/or  <br /><br />
3.	if you are participating in any event that provides transportation assistance. <br /><br /> 
Claims<br /><br />
If you require ground transportation as the result of a covered loss, please call: <br /><br /> 
	StarrCYCLE/SPOKE Roadside Assistance HOT LINE 1 (888) 262-2699<br /><br />
All other terms and conditions of this policy remain unchanged.  
</div> ';
?>

Open in new window


main-page.php
<?php
include( 'forms/documents.php' );
echo $toca; (THIS WORKS)

$check_alt  = 	"SELECT meta_value, meta_key
					FROM wp_woocommerce_order_itemmeta
					WHERE meta_key = 'State'
					AND order_item_id = :order_id ";
 
		$checking_alt = $pdo->prepare($check_alt);		
		$checking_alt->execute(array(':order_id' => $order_id)) or die(print_r($checking_alt -> errorInfo()));
		$res_alt = $checking_alt->fetchAll();	
				
				if ($res_alt) {
					
					foreach ($res_alt as $rows)  {
						if($rows->meta_key == "Statel") { 
							$st = $rows->meta_value;
						}
if ( $st == "10") {
	$toc = $toca;
} else {
	$toc = '';
}

echo $toc;
?>

Open in new window


The Warning comes at main -page.php on line 21.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 40340233
That cannot possibly be an EXACT copy of the scripts, unless you have never run them.  The main-page script will fail for a parse error on line 3.  There's a reason why we ask for EXACT copies - because we cannot help you if we get extraneous information or abstractions that hide the true problems.

Please post the EXACT scripts as you have them now.
0
 
LVL 7

Author Comment

by:rgranlund
ID: 40340239
It's really really big.  I just want to include variable from another page.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 40340376
The design pattern shown here teaches exactly how to do it.  I expect that the reason your "really really big" script failed is a logic error that leads to a variable not getting set.  That is one of the reasons we, as an industry, are moving away from big complicated scripts to object-oriented programming, with smaller, simpler scripts.  It's very difficult to debug big scripts and almost impossible to test them correctly.  And without rigid enforcement of programming standards, it's really easy to get tripped up by the logic errors.

Let me try to show you an example of the value of programming standards.  The two standards illustrated here are (1) indent each control structure 4 spaces and (2) line up braces for each control structure.  Here is the original "main" script from this post.  Look at it and see if you can tell why it's going to fail.

<?php
include( 'forms/documents.php' );
echo $toca; (THIS WORKS)

$check_alt  = 	"SELECT meta_value, meta_key
					FROM wp_woocommerce_order_itemmeta
					WHERE meta_key = 'State'
					AND order_item_id = :order_id ";
 
		$checking_alt = $pdo->prepare($check_alt);		
		$checking_alt->execute(array(':order_id' => $order_id)) or die(print_r($checking_alt -> errorInfo()));
		$res_alt = $checking_alt->fetchAll();	
				
				if ($res_alt) {
					
					foreach ($res_alt as $rows)  {
						if($rows->meta_key == "Statel") { 
							$st = $rows->meta_value;
						}
if ( $st == "10") {
	$toc = $toca;
} else {
	$toc = '';
}

echo $toc;
?>

Open in new window

Now look at the same code, but with the programming standards applied.  It's easy to see in an instant that the control structures are incomplete, leading to a parse error or logic failure at run time.

<?php // demo/temp_rgranlund_main.php
error_reporting(E_ALL);

include( 'forms/documents.php' );
echo $toca; // (THIS WORKS)

$check_alt 
= 
"
SELECT meta_value, meta_key
FROM wp_woocommerce_order_itemmeta
WHERE meta_key = 'State'
AND order_item_id = :order_id
"
;

try
{
    $checking_alt = $pdo->prepare($check_alt);
    $checking_alt->execute(array(':order_id' => $order_id));
    $res_alt = $checking_alt->fetchAll();
}
catch(PDOException $e)
{
    trigger error($e->getMessage(), E_USER_ERROR);
}

if ($res_alt)
{
    foreach ($res_alt as $rows)
    {
        if($rows->meta_key == "Statel") // THIS CANNOT OCCUR BECAUSE OF THE QUERY
        {
            $st = $rows->meta_value;
        }
        if ( $st == "10")
        {
            $toc = $toca;
        }
        else
        {
            $toc = '';
        }

        echo $toc;
?>

Open in new window

Executive summary: I would recommend you adopt a coding standard and adhere to it.  You will not have "mystery problems" like this missing variable if you're meticulous about neatness and adherence to standards.
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

"In order to have an organized way for empathy mapping, we rely on a psychological model and trying to model it in a simple way, so we will split the board to three section for each persona and a scenario and try to see what those personas would Do,…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now