Solved

How to rewrite php code with function

Posted on 2013-06-28
15
427 Views
Last Modified: 2013-06-29
I have some PHP code that sends email if certain criteria are met.  It works fine.  But I have to send to multiple recipients based upon different criteria, so I'm trying to move part of the code into a function that can be run each time any of the criteria are met.

Here's the code that works:

if ( ( something ) && ( somethingelse ) ) {

	// Start output buffering
	ob_start();  
	include '_notes/php/email-receipt/page.php';
	$buffer = ob_get_contents();
	ob_end_clean();
	
	$to       = "someone@school.edu>";
	$subject  = "New Online Enrollment";
	$headers  = "MIME-Version: 1.0" . "\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1" . "\n";
	$headers .= "From: " . "guy@domain.com" . "\n";
	$message  = $buffer;
	
	mail($to, $subject, $message, $headers);
}

Open in new window

I'm trying to move the output buffering scheme into a function, but it's not working.  Here's the reworked code I've tried:

getMailBody() {
	ob_start();  
	include '_notes/php/email-receipt/page.php';
	$buffer = ob_get_contents();
	ob_end_clean();
	return $buffer;
}

if ( ( something ) && ( somethingelse ) ) {

	$to       = "someone@school.edu>";
	$subject  = "New Online Enrollment";
	$headers  = "MIME-Version: 1.0" . "\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1" . "\n";
	$headers .= "From: " . "guy@domain.com" . "\n";
	$message  = getMailBody();
	
	mail($to, $subject, $message, $headers);
}

Open in new window

Can anyone tell me what I'm doing wrong?

Thanks!
0
Comment
Question by:Jonathan Greenberg
  • 7
  • 3
  • 3
  • +1
15 Comments
 
LVL 34

Assisted Solution

by:gr8gonzo
gr8gonzo earned 167 total points
ID: 39285725
My guess is that _notes/php/email-receipt/page.php might contain references to global variables, which would not be available in the function scope unless you intentionally global them in before you do your include, like:

global $var1, $othervar2;
include("_notes/php/email-receipt/page.php");
...etc...
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 167 total points
ID: 39285771
it's not working
What is the symptom of failure?  If it's a parse error, try this code snippet.

function getMailBody() {
	ob_start();  
	include '_notes/php/email-receipt/page.php';
	$buffer = ob_get_contents();
	ob_end_clean();
	return $buffer;
}

if ( ( something ) && ( somethingelse ) ) {

	$to       = "someone@school.edu>";
	$subject  = "New Online Enrollment";
	$headers  = "MIME-Version: 1.0" . "\n";
	$headers .= "Content-type: text/html; charset=iso-8859-1" . "\n";
	$headers .= "From: " . "guy@domain.com" . "\n";
	$message  = getMailBody();
	
	mail($to, $subject, $message, $headers);
}

Open in new window

0
 

Author Comment

by:Jonathan Greenberg
ID: 39285839
Well, Ray, you certainly caught one obvious deficiency in my script: I didn't declare my function a function!  (OK, I'm an idiot!)

I've made that correction.  And I expected that would do it, but it's still not working, although I can see that the process is advancing further.

I realize "it's not working" doesn't provide much to go on.  There are a number of scripts interacting here, and I'm afraid I haven't figured out a way to make the page I'm coding display its error message on the web page that results.

gr8gonzo, I don't think I used any global variables in _notes/php/email-receipt/page.php.  I'm going to post the code of that page below.

The result of running this script is that an email is sent.  The script that creates the email body is on _notes/php/email-receipt/page.php.  When the script that this question is about is run, _notes/php/email-receipt/page.php queries my database, fills in a bunch of fields and creates the body of my email message.  Done my original way, it works.  Done this new way, with the output buffering moved into a function, the message body is still generated and the email sent, but it appears that the database is not being successfully queried, because all the expected fields are blank and all dates are December 31, 1969.

So I'm still at a loss as to what the problem is.

Following is the code from _notes/php/email-receipt/page.php, just in case that enables anyone to help me figure out what's going wrong.

Thanks very much!

<?php
error_reporting(0);
include_once('_notes/php/db.inc.php');

$result = mysql_query("SELECT * FROM mytable WHERE inv=".$myarray[7]);

while ( $row = mysql_fetch_assoc($result) ) {
	$policy 		= $row['polic'];
	$plan 			= $row['pla'];
	$underwriter 	= $row['underwrit'];
	$benefit 		= $row['benef'];
	$policy_info 	= $row['polic'];
	$ppo 			= $row['ppo'];
	$sch_yr 		= $row['school_yea'];
	$underwriter 	= $row['underwrite'];
	$lastname 		= $row['lastn'];
	$firstname 		= $row['firstn'];
	$middle 		= $row['mid'];
	$student_id 	= $row['student_i'];
	$school 		= $row['sch'];
	$pay_type 		= $row['pay_t'];
	$total_amount 	= $row['total_am'];
	$major_med 		= $row['optiona'];
	$ic_sports 		= $row['interco'];
	$category 		= $row['categ'];
	$stud_status 	= $row['stud_stat'];
	$spouse 		= $row['spous'];
	$child1 		= $row['chil1'];
	$child2 		= $row['chil2'];
	$child3 		= $row['chil3'];
	$cov_period 	= $row['coverage_p'];
	$eff_date 		= $row['eff_d'];
	$ter_date 		= $row['ter_d'];
	$rct_comment_1 	= $row['rct_comt_1'];
	$rct_comment_2 	= $row['rct_comt_2'];
}

setlocale(LC_MONETARY, "en_US");
$total_amount = money_format("%n",$total_amount);
$eff_date = date( "F j, Y",strtotime($eff_date) );
$ter_date = date( "F j, Y",strtotime($ter_date) );
$please_advise = "If we can be of further assistance, or if you find discrepancies<br />in the above information, please advise.";
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>IFS Receipt</title>
</head>
<body>
<div style="margin: 10px auto;width: 580px;font-size: 15px;font-family: Times New Roman, Georgia, serif;">

<div id="heading" style="float: left;margin-top: 60px;">
  <span class="title" style='font-size: 32px;'>RECEIPT</span><br />
  <?php echo date("F j, Y") . "\n";?>
</div>
<?php
echo "<div id='plan_data' style='text-align: center;margin: 130px 0 0;font-size: 18px;font-weight: bold;'>\n";
echo "  <p>{$sch_yr} SCHOOL YEAR<br />\n";
echo "    {$plan} <br />\n";
echo "    POLICY # {$policy}\n";
echo "  </p>\n";
echo "  <p>POLICY UNDERWRITTEN BY<br />\n";
echo "    " . strtoupper($underwriter);
if ( !empty($ppo) ) {
	echo "<br />\n    {$ppo}\n";
}
else {
	echo "\n";
}
echo "  </p>\n";
echo "</div>\n";

echo "<div id='insured'><hr>\n";
echo "  <p><b>INSURED</b>: ";
echo "{$firstname} ";

if ( !empty($middle) ) {
	echo "{$middle}. ";
}
echo "{$lastname} <br />\n";
echo "    <b>STUDENT ID</b>: {$student_id}<br />\n";
echo "    <b>SCHOOL</b>: {$school}\n";
echo "  </p>\n";
echo "</div>\n";
echo "<div id='payment' style='margin: 12px 0 0;'>\n";
echo "  <p>\n    <b>PAYMENT RECEIVED</b>: ";
echo "{$pay_type} for {$total_amount}\n";
echo "  </p>\n";
echo "</div>\n";
echo "<div id='coverage' style='margin: 12px 0 0;'>\n";
echo "  <b>COVERAGE PURCHASED</b>:<br />\n";
echo "  <p style='margin: 6px 0 0 36px;'>";
if ( ( $plan != "Stetson University" ) && ( $plan != "Florida Atlantic University" ) ) {
	echo "{$plan}<br />\n";
}
if ( !empty($benefit) ) {
	echo "{$benefit}<br />\n";
}
if ( !empty($policy_info) ) {
	echo "{$policy_info}<br />\n";
}
if ( !empty($major_med) ) {
	echo "Optional Major Medical Coverage<br />\n";
}
if ( !empty($ic_sports) ) {
	echo "Optional Sports Rider<br />\n";
}
echo "  </p>\n";
echo "</div>\n";
echo "<div id='purchased_for' style='margin: 12px 0 0;'>\n";
echo "  <b>INSURANCE PURCHASED FOR</b>:\n";
echo "  <p style='margin: 6px 0 0 36px;'>";
if ( $plan == "Florida University" ) {
	if ( ( $category == "Domestic" ) || ( $category == "International" ) ) {
		echo "{$category} Student<br />\n";
	}
	else {
		echo "{$category}<br />\n";
	}
}
else {
	if ( !empty($stud_status) ) {
		echo "{$stud_status}<br />\n";
	}
	else {
		echo "Student<br />\n";
	}
}
echo "  </p>\n";
echo "</div>\n";
if ( ( !empty($spouse) ) || ( !empty($child1) ) || ( !empty($child2) ) || ( !empty($child3) ) ) {
	echo "<div id='dependents' style='margin: 12px 0 0;'>\n";
	echo "  <b>DEPENDENT COVERAGE</b>:";
	echo "  <p>\n";
	if ( !empty($spouse) ) {
		echo "    <b>Spouse</b>: {$spouse}<br />\n";
	}
	if ( !empty($child1) ) {
		echo "    <b>Child</b>: {$child1}<br />\n";
	}
	if ( !empty($child2) ) {
		echo "    <b>Child</b>: {$child2}<br />\n";
	}
	if ( !empty($child3) ) {
		echo "    <b>Child</b>: {$child3}<br />\n";
	}
	echo "  </p>\n";
	echo "</div>\n";
}
echo "<div id='period' style='margin: 12px 0 0;'>\n";
echo "  <b>PERIOD OF COVERAGE SELECTED</b>: {$cov_period}";
echo "</div>\n";

echo "<div id='cov_dates' style='margin: 12px 0 0;'>\n";
echo "  <b>DATES OF COVERAGE:</b>\n";
echo "  <p style='margin: 6px 0 0 36px;'>\n    <b>Effective Date</b>: {$eff_date}<br />\n";
echo "    <b>Termination Date</b>: {$ter_date}<br />\n";
echo "  </p>\n";
echo "</div>\n";

echo "<div id='note' style='margin: 18px 0 0;text-align: center;font-style: italic;'><hr>\n";
echo "  <p>{$please_advise}";
echo "  </p>\n";
echo "</div>\n";
?>
</div>
</body>
</html>

Open in new window

0
 

Author Comment

by:Jonathan Greenberg
ID: 39285881
Hold on.  I don't want to waste anyone's time, and I think I've found something else that may be causing the problem.  Please, if anyone is interested in helping, hold off until I post again.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39285908
Please change line 2 from this:

error_reporting(0);

to this:

error_reporting(E_ALL);
0
 

Author Comment

by:Jonathan Greenberg
ID: 39285909
Please ignore my prior post at ID: 39285881.  No additional cause of this problem was found.  The status of this question is as it was at ID: 39285839.

Sorry for the confusion!
0
 

Author Comment

by:Jonathan Greenberg
ID: 39285940
Thanks, Ray.  I did that, but I'm still not seeing an error message.  The place where I'm supposing the error message would show up is in the resulting email, but there's none there.

Below is the resulting email.  The first one is generated with my original code, the 2nd is generated with the output buffering moved into a function.

RECEIPT
June 28, 2013
My Company, Inc.
123 Main Street
Any Town, CA 12345
Phone: (222) 222-1234 / (800) 222-1234
Fax: (222) 222-1234

2012-2013 SCHOOL YEAR
International Student/Scholar Accident & Sickness Health Insurance Plan
POLICY # 0123-4567-2345

POLICY UNDERWRITTEN BY
AMERICAN INSURANCE COMPANY

INSURED: Jonathan A. Test
STUDENT ID: 12345678
SCHOOL: Some College

PAYMENT RECEIVED: Charge for $1,329.00
COVERAGE PURCHASED:

International Student/Scholar Accident & Sickness Health Insurance Plan
$250,000 Maximum Benefit per Injury/Sickness
Repatriation & Medical Evacuation provided by FrontMEDEX
INSURANCE PURCHASED FOR:

Student
PERIOD OF COVERAGE SELECTED: Annual
DATES OF COVERAGE:

Effective Date: August 21, 2013
Termination Date: August 20, 2014

If we can be of further assistance, or if you find discrepancies
in the above information, please advise.
___________________________________________________________________
RECEIPT
June 28, 2013
My Company, Inc.
123 Main Street
Any Town, CA 12345
Phone: (222) 222-1234 / (800) 222-1234
Fax: (222) 222-1234

SCHOOL YEAR

POLICY #

POLICY UNDERWRITTEN BY

INSURED:
STUDENT ID:
SCHOOL:

PAYMENT RECEIVED: for $0.00
COVERAGE PURCHASED:


INSURANCE PURCHASED FOR:

Student
PERIOD OF COVERAGE SELECTED:
DATES OF COVERAGE:

Effective Date: December 31, 1969
Termination Date: December 31, 1969

If we can be of further assistance, or if you find discrepancies
in the above information, please advise.

Open in new window

0
Control application downtime with dependency maps

Visualize the interdependencies between application components better with Applications Manager's automated application discovery and dependency mapping feature. Resolve performance issues faster by quickly isolating problematic components.

 
LVL 58

Expert Comment

by:Gary
ID: 39285987
I only had a quick look at your code, but you are using $myarray[7] (did not look for any other variables) in your email code, which is called from a function that does not have the variable.
Functions are localized. If you want to access a variable that exists outside the function you would have to use GLOBALS or pass the value into the function.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39286048
The error message would not show up in the email.  It would show up in your error_log (or some file with a similar name on the server).  You might want to ask the server administrator to be certain that the errors are being logged.

In software development there is a concept that we call the SSCCE.  It is guidance that leads the developer in the direction of reducing the problem to isolate the point of failure.  Once isolated, problems are easier to solve, or as Charles Kettering put it, "A problem well stated is a problem half solved."

You might find the easiest way to debug this would be to start over -- use something simple that meets a part of the needs, then gradually build the programming back up, step-by-step, to a fully-fledged application.   Test each step along the way.  As soon as you find a point of failure, you have something that you can attack.
0
 

Author Comment

by:Jonathan Greenberg
ID: 39286114
Thank you, Ray.  There are error_log files in several directories, one dated only yesterday, but none in the directory where these two scripts reside.  So it appears that errors are being logged, yet there's none for this script that I'm aware of.  I'll have to look into that.

And thanks for taking a moment to educate me.  I really appreciate that!

Gary, perhaps it's because of my relative inexperience with php, but my thinking is that since the function has no need for the data in the global variable $myarray[7], only for the data returned by the include page that it's calling, there's no need for the function to access that variable.  Nevertheless, I placed 'global $myvariable;' within my function, which is I think what you were suggesting, but it made no difference.

Without a doubt, my lack of php expertise, as compared to many of you here on EE, is limiting my ability to comunicate effectively.  But I guess all I can do is my best.  Sorry if that results in your time being wasted, and I'm grateful for all the attempts at helping me that have been made!
0
 
LVL 58

Accepted Solution

by:
Gary earned 166 total points
ID: 39286145
For someone starting out in programming it would be a common misconception that variables exist everywhere but it's not true.
When I said a function is localised that means any values set in the function are contained within the function and do not exist outside that function, in the reverse, variables that exist outside the function are not accessible within the function. Unless they are global functions.

Your function includes the code from the email page where you use $myarray[7].
Using include is basically the same as writing that external code within the function itself so yes - this variable needs to be accessible within the function.
The easiest way to pass this data when calling the function is to pass it along i.e. when you use getMailBody(), instead pass that that value to the function - so to call the function you use
getMailBody($myarray[7])
Your function would then start
function getMailBody(myParam){...}
...then in that email code page instead of using $myarray[7] you would use myParam
Obviously myParam is just an example of a name - you would use whatever is most obvious to you

Unless of course I'm reading thru your code wrong...
0
 

Author Comment

by:Jonathan Greenberg
ID: 39286214
Gary, thank you so much, it looks like that did it!  I'm exhausted from many hours of writing code that's way above my pay grade (not to mention knowledge level), so I need to look it over in the morning to make sure I'm not hallucinating -- but I think I'm good!

Thanks, I'll be in touch tomorrow.  And thanks so much for your explanation, it really helps.

Regards,
Jon
0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 39286738
Gary elaborated on what I was trying to say initially about variable scopes, so it's good that that was the answer.

On a side note - if you have access to change the PHP.ini file and restart the web server, I usually find it useful to log my PHP errors to a file in case they are suppressed on the page or happen in a strange location. This is done with:

log_errors = On
error_log = C:\path\to\errors.log
0
 
LVL 58

Expert Comment

by:Gary
ID: 39286760
gr8gonzo is correct I never noticed his comment/read it properly
0
 

Author Comment

by:Jonathan Greenberg
ID: 39287069
I'm all set here, this is now working.

gr8gonzo, it wasn't lost on me that Gary was elaborating on your original point, which did seem to reflect my issue.  It was my lack of knowledge that left me unable to take advantage of your earlier answer.  When Gary pointed out in excruciatingly basic terms how to pass the value to the function, I was finally able to successfully test your solution.

Thanks, too, for your side note, which Ray_Paseur was similarly encouraging me to look into.  I'm having a bit of a problem with configuring my php.ini file, but I'll address that in a separate question.

And it was Ray who pointed out in his code snippet my very first and most basic mistake, that I hadn't declared my function.

Thanks to Ray, Gary and gr8gonzo for some really helpful answers which have not only solved the immediate problem but also helped me to improve as a programmer.  I wish I had more points to allocate.  Heartfelt thanks to all!
0

Featured Post

Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

Join & Write a Comment

Suggested Solutions

In Solr 4.0 it is possible to atomically (or partially) update individual fields in a document. This article will show the operations possible for atomic updating as well as setting up your Solr instance to be able to perform the actions. One major …
Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL (http://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL.html) several years ago, it seemed like now was a good time to updat…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

743 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

11 Experts available now in Live!

Get 1:1 Help Now