Solved

PHP if statement as one variable

Posted on 2013-01-28
15
225 Views
Last Modified: 2013-02-01
Hi all,

I have setup a function using fpdf which allows the exporting of a user's text entries records to a pdf document. In order to export it all of the output needs to be saved in the variable called $text.

Here is the code I am using to get all of the user's entries and am printing them on the screen for the user to see. I would like them to be displayed similarly in the pdf document I am creating for them. If someone could show me how to save the results in this variable that would be great.

<?php
			if ( ! isset($_POST["search_journal"]) )
			{
				if ( isset($_GET["dt"]) ) // show 1 day, selected from calendar
				{
					$query = mysql_query("SELECT * FROM journal_table WHERE user_id = '$username' AND DATE_FORMAT(entry_timestamp, '%Y%m%d') = '{$_GET["dt"]}' ORDER BY entry_id DESC") or die ( mysql_error() );
				}
				else
				{
								$select_all = false;
								
								if ( ! isset($_POST["FilterRow"]) )
								{
									$limit = 5; // default
								}
								else if ( $_POST["FilterRow"] == "all" )
								{
									$select_all = true;
								}
								else
								{
									$limit = (int)$_POST["FilterRow"];
								}
								
								if ( $select_all )
								{
									$query = mysql_query("SELECT * FROM journal_table WHERE user_id = '$username' ORDER BY entry_id DESC") or die ( mysql_error() );
								}
								else
								{
									$query = mysql_query("SELECT * FROM journal_table WHERE user_id = '$username' ORDER BY entry_id DESC LIMIT $limit") or die ( mysql_error() );
								}
				}

								$total_things = mysql_num_rows($query);
								
								if ( $total_things == 0 )
								{
									echo "You do not seem to have posted any journal! Why don't you start? :) ";
								}
								else
							{
								while ( $row = mysql_fetch_array($query) )
								{
								$post_id = $row["entry_id"];
								$date = $row["entry_timestamp"];
								$day = date('d',strtotime($date));
								$month = date('F',strtotime($date));
								?>
						<div id = "Content">
										<div id = "Side">
												<div id = "Entry_Month"><?php echo $month; ?></div>
												<div id = "Entry_Day"><?php echo $day; ?></div>									
											<img height = "70px" width = "50px" src = "<?php echo $URL; ?>">
										</div>
										<div id = "Journal">
											<p id = "Journal_Title"><?php echo $row["entry_title"]; ?></p>
											<p id = "Journal_Sender"><?php echo "By: " . $username; ?></p>
											<p id = "Journal_Content"><?php echo $row["entry_text"];?></p>
											<div class = "Seperator"><hr></div>
											<p id = "Journal_Timestamp"><?php echo $date . " - <a href = 'editjournal.php?id=$post_id'>Edit</a> - <a href = 'deletejournal.php?id=$post_id'>Delete</a>";?></p>
										</div>
						<div class = "ClearFloat"></div>
						<div class = "Seperator"><hr></div>
						</div>
								<?php
								}
							}			
			}
			else
			{
								$term = $_POST["search_journal"];
			
								$query = mysql_query("SELECT * FROM journal_table WHERE entry_text LIKE '%$term%' OR entry_title LIKE '%$term%' ORDER BY entry_id DESC") or die ( mysql_error() );
								
								$total_things = mysql_num_rows($query);
								
								if ( $total_things == 0 )
								{
									echo "No Result For The Term Selected.<br><br>";
								}
								else
							{
								while ( $row = mysql_fetch_array($query) )
								{
								$post_id = $row["entry_id"];
								?>
						<div id = "Content">
										<div id = "Journal" style = "width: 100%;">
											<p id = "Journal_Title"><?php echo $row["entry_title"]; ?></p>
											<p id = "Journal_Sender"><?php echo "By: " . $row["user_id"]; ?></p>
											<p id = "Journal_Content"><?php echo $row["entry_text"];?></p>
											<div class = "Seperator"><hr></div>
											<p id = "Journal_Timestamp"><?php echo $row["entry_timestamp"] . " - <a href = 'editjournal.php?id=$post_id'>Edit</a> - <a href = 'deletejournal.php?id=$post_id'>Delete</a>";?></p>
										</div>
						<div class = "ClearFloat"></div>
						<div class = "Seperator"><hr></div>
						</div>
								<?php
								unset($_POST["search_journal"]);
								}
							}				
			}
			

		?>

Open in new window

0
Comment
Question by:TLN_CANADA
  • 8
  • 3
  • 2
  • +1
15 Comments
 

Author Comment

by:TLN_CANADA
ID: 38825919
If it helps, here is the include file for the pdf exporter, you can see the $text variable here that is printed in the pdf document

<?php 
error_reporting(E_ALL);



$font = 'Arial';

// BRING IN THE PDF THING
require_once('fpdf/fpdf.php');

// SYNTHESIZE THE PDF FILE INFORMATION
$pdf_file_link
= DIRECTORY_SEPARATOR
. 'RAY_junk'
. DIRECTORY_SEPARATOR
. 'temp_pdf_blue'
. '.pdf'
;
$pdf_file_name
= getcwd()
. $pdf_file_link
;

$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont($font, 'B', 16);
$pdf->SetFillColor(  0,   0, 255);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(40, 10, $text, 0, 2, 'L', TRUE);

// WRITE THE PDF TO DISK
$pdf->Output($pdf_file_name, 'F');

// PRESENT A LINK
echo '<a target="my_PDF" href="' . $pdf_file_link . '">Blue PDF</a>';


?>

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 38825964
You can use ob_start and ob_get_clean

put ob_start() before you start outputting the text. When you are done doe the following

$text = ob_get_clean();

$text now has what would have been on the screen.

Refer to the man page for ob_get_clean for more information and samples

http://php.net/manual/en/function.ob-get-clean.php
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 38826431
ob_start() will enable you to capture all of the browser output.  However that will include the HTML statements and those are probably not exactly what you want in the PDF document.

What you've got here is a common problem for new PHP programmers.  You can bounce back and forth between PHP and HTML, but just because you can does not mean that you should.  Programming like that will make your work products unmaintainable and unextensible.  It's fine if you want to work alone but as soon as you start trying to get cooperation from another programmer, you have a mess on your hands.

I recommend two things.  First, learn about HEREDOC notation.  It's a great way to get PHP variable values embedded into HTML documents.  And second, accept the fact that PDF is a document layout language, whereas HTML is a semantic markup language.  These are not quite as different as fish and bicycles, but almost that different.  You will find the work will go well when you write two separate scripts - one for HTML and a separate one for PDF.  The data acquisition methods can be shared between these scripts, but the output processes need to be completely separate.

Best regards and best of luck with it, ~Ray
0
 
LVL 82

Accepted Solution

by:
hielo earned 200 total points
ID: 38826910
<?php
	$text='';
			if ( ! isset($_POST["search_journal"]) )
			{
				if ( isset($_GET["dt"]) ) // show 1 day, selected from calendar
				{
					$query = mysql_query("SELECT * FROM journal_table WHERE user_id = '$username' AND DATE_FORMAT(entry_timestamp, '%Y%m%d') = '{$_GET["dt"]}' ORDER BY entry_id DESC") or die ( mysql_error() );
				}
				else
				{
								$select_all = false;
								
								if ( ! isset($_POST["FilterRow"]) )
								{
									$limit = 5; // default
								}
								else if ( $_POST["FilterRow"] == "all" )
								{
									$select_all = true;
								}
								else
								{
									$limit = (int)$_POST["FilterRow"];
								}
								
								if ( $select_all )
								{
									$query = mysql_query("SELECT * FROM journal_table WHERE user_id = '$username' ORDER BY entry_id DESC") or die ( mysql_error() );
								}
								else
								{
									$query = mysql_query("SELECT * FROM journal_table WHERE user_id = '$username' ORDER BY entry_id DESC LIMIT $limit") or die ( mysql_error() );
								}
				}

				$total_things = mysql_num_rows($query);
								
				if ( $total_things == 0 )
				{
					$text.="You do not seem to have posted any journal! Why don't you start? :) ";
				}
				else
				{
					while ( $row = mysql_fetch_array($query) )
					{
						$post_id = $row["entry_id"];
						$date = $row["entry_timestamp"];
						$day = date('d',strtotime($date));
						$month = date('F',strtotime($date));
						
						$text.='
						<div id = "Content">
										<div id = "Side">
												<div id="Entry_Month">'.$month.'</div>
												<div id="Entry_Day">'.$day.'</div>									
											<img height="70px" width = "50px" src = "'.$URL.'">
										</div>
										<div id="Journal">
											<p id="Journal_Title">'.$row["entry_title"].'</p>
											<p id="Journal_Sender">By: '.$username.'</p>
											<p id="Journal_Content">'.$row["entry_text"].'</p>
											<div class="Seperator"><hr></div>
											<p id="Journal_Timestamp">'.$date . " - <a href='editjournal.php?id=$post_id'>Edit</a> - <a href = 'deletejournal.php?id=$post_id'>Delete</a>".'</p>
										</div>
						<div class="ClearFloat"></div>
						<div class="Seperator"><hr></div>
						</div>';
					}
				}			
			}
			else
			{
				$term = $_POST["search_journal"];
			
				$query = mysql_query("SELECT * FROM journal_table WHERE entry_text LIKE '%$term%' OR entry_title LIKE '%$term%' ORDER BY entry_id DESC") or die ( mysql_error() );
								
				$total_things = mysql_num_rows($query);
							
				if ( $total_things == 0 )
				{
					$text.="No Result For The Term Selected.<br><br>";
				}
				else
				{
					while ( $row = mysql_fetch_array($query) )
					{
						$post_id = $row["entry_id"];

						$text.='
						<div id = "Content">
										<div id="Journal" style="width: 100%;">
											<p id="Journal_Title">'.$row["entry_title"].'</p>
											<p id="Journal_Sender">By: '.$row["user_id"].'</p>
											<p id="Journal_Content">'.$row["entry_text"].'</p>
											<div class="Seperator"><hr></div>
											<p id = "Journal_Timestamp">'.$row["entry_timestamp"] . " - <a href='editjournal.php?id=$post_id'>Edit</a> - <a href='deletejournal.php?id=$post_id'>Delete</a>".'</p>
										</div>
						<div class="ClearFloat"></div>
						<div class="Seperator"><hr></div>
						</div>';

						unset($_POST["search_journal"]);
					}
				}				
			}
		?>

Open in new window

0
 

Author Comment

by:TLN_CANADA
ID: 38827992
Thank you Ray for your helpful advice.
0
 

Author Comment

by:TLN_CANADA
ID: 38827999
Hi hielo,

This does not print any output by putting the text variable in this position. Let me know if there is anything else I can do it with.

Thanks,

D
0
 

Author Comment

by:TLN_CANADA
ID: 38830066
Hi julian,

Could you give me an example of how to do this using the query I provided? I've tried this diferrent ways but any way I do it, it does not print the original query information on the page.

Thanks,

D
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 200 total points
ID: 38830625
...it does not print the original query information...
It's not feasible for us to write your scripts for you, and usually we can offer suggestions but you're the one who has the test data, so you have to be the one who interprets and implements these suggestions.  The post from julianH will load the contents of the browser output buffer into a variable named $text.  You might want to examine this variable to see what is present in the variable.

To examine a variable you must employ a two-step process.  First, use PHP var_dump() to print out the contents of the variable.  Second, use your browser "View Source" feature to see past the HTML tags so you can truly discern what's in the variable.

Computer programming only does one thing: It changes the form of data from one form to another form.  That is all.  So it would follow that the essential knowledge is to understand the form of the data at every step in the process.  If you're like most of us you will find that var_dump() is your friend because it gives you visual representations of the data.  You cannot use it too often during the development process!
0
 
LVL 82

Expert Comment

by:hielo
ID: 38831546
are you including the pdf exporter from within a function and $text is declared outside that function?
If yes, try putting:

global $text;

at the beginning of that function.
0
 

Author Comment

by:TLN_CANADA
ID: 38833431
Thanks hielo, I'll give that a go.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 38833866
http://en.wikipedia.org/wiki/Encapsulation_%28object-oriented_programming%29

If you're working alone and nobody else will ever see or contribute to your code, you can probably ignore these concepts, and the world will not start hating on your program code because it will never uncover your program code.  

Good programming practices are not "good" for some abstract reason; they are good because they reduce errors, especially run-time errors, such as variable name collisions.  If your work has some economic value you might want to get some structured training in the principles of computer science and especially the principles of object-oriented programming as implemented in PHP.  Or at least give yourself some time to study the basics.

Best of luck with your project, ~Ray
0
 

Author Comment

by:TLN_CANADA
ID: 38833881
Thank you Ray for this advice. I will check these links out.
0
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 100 total points
ID: 38833941
sorry for the late reply.

The ob_start captures the output text to a buffer so it won't display on the screen - however this is easily resolved by simply echoing the $text variable at the end of the code so.

ob_start()

// Do your query and output here

$text = ob_get_clean();

echo $text;
//Output is as before but it is now also in the $text variable

Open in new window

0
 

Author Comment

by:TLN_CANADA
ID: 38834131
Thanks julianH, that's helpful. I think we almost have it now but the formatting is a real pain on it.
0
 

Author Comment

by:TLN_CANADA
ID: 38845527
Thanks everyone, it took a while but we have this formatted now :)
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

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

10 Experts available now in Live!

Get 1:1 Help Now