PHP: Whole HTML page as variable - is there a better way? - php

I have a large form, in the end of the form a user is presented with a summary:
You have entered:
<table>
<tr>
<td>First name</td>
<td><?php echo $firstname ?></td>
</tr>
<tr>
<td>Last name</td>
<td><?php echo $lastname ?></td>
</tr>
</table>
I first designed the summary page and now the thought came to me that it would be nice to send the user this page as a confirmation e-mail. What I have done now is this:
<?php $summarypage = "<table>
<tr>
<td>First name</td>
<td>".$firstname."</td>
</tr>
<tr>
<td>Last name</td>
<td>".$lastname."</td>
</tr>
</table>";
echo $summarypage; ?>
For loops I use $summarypage .= "blabla"; within the loops.
When sending the e-mail I can just take $summarypage and attach it to my e-mail body. Beautiful.
Is what I am doing OK? It seems very "not elegant" to me.
Isn't $summarypage being rendered totally anew when I call it again in my e-mail - meaning all variables concatenated with it (e.g. $firstname) will be called again - performance hog?
Is there some kind of "buffer" I could just write the $summarypage variable to, so I have a plain-text variable afterwards? Would $newsummarypage = string($summarypage) do the trick?

Ignore performance on that level, it won't matter. If the method you show works for you, use it.
An alternative that makes things a bit more readable (because you won't need PHP openers / closers) is HEREDOC:
<?php $summarypage = <<<EOT
<table>
<tr>
<td>First name</td>
<td>$firstname</td>
</tr>
<tr>
<td>Last name</td>
<td>$lastname</td>
</tr>
</table>
EOT;
?>

I think you are a bit confused about how strings/variables work in php. A little example might help
$s = "hello"; //stores the sequence 'h' 'e' 'l' 'l' 'o' in $s
$s = $s." world";//take the sequence stored in $s add the sequence ' world',
//and store in $s again
echo $s; // prints 'hello world'. That is what $s contains, what $s is
$summary = "<div>".$firstname."</div>"; // take '<div>', lookup what $firstname
//contains and add that, then add '</div>' and then store this
//new string thing('<div>Ishtar</div>') in $summary.
echo $summary; //$summary here knows nothing about $firstname,
//does not depend on it
All variables are evaluated when you use them. (Well, most of the time you use variables by evaluating them.)

$summarypage is a string, so it's just a bit of data assigned to a variable - a plain-text variable, as you said. Once the data is assigned to $summarypage, the work is done. You can happily write it out into pages, emails, databases and text files with no additional performance hits related to $summarypage.

Related

How to do href in php

At the beginning I would like to say that this is my first post and I apologize in advance for any possible mistakes. And these are my beginnings in programming.
I have a problem with appropriate action download.php in the following code snippet:
<?php
$cv= $row[25];
$output .= '
<tr>
<td> <a href='download.php?dow=$cv'>Download</a> </td>
</tr>
';
?>
I wish it worked like the following code (in which it operates correctly):
<tr>
<td><?php echo "<a href='download.php?dow=$cv'>Download</a><br>"; ?></td>
</tr>
You need to concatenate the string. To concatenate you use a dot . This will put the variable value inside your string.
<?php
$output .= "
<tr>
<td><a href='download.php?dow=".$cv."'>Download</a> </td>
</tr>
";
you closed string before it's even finished!
the $output is a variable and you tried to store the HTML as an string inside it, but you've closed the ' sign before the download.php?dow=$cv and then opened it again. the correct way to write it is:
<?php
$cv= $row[25];
$output .= "
<tr>
<td> Download </td>
</tr>
";
?>
the \ before " called escaping and is needed because we dont want to end our string! just want to add that quote sign as a character like the others.

Put text between autofilled PHP-Table

I'm currently working on a table that contains 'Name', 'Info', 'Price' and 'Duration'. However the PHP-Script is connected to a database.
I want to autofill the tablecells: 'Name', 'Price', 'Duration' via the Database by using PHP and SQL and that works perfectly fine for me. Though, I want to customize the content that's in the individual Info cells (e.g. Readmore jQuery and redirect to other pages).
I tried a little bit with using tags inside the Database and other weird stuff which, obviously, didn't work.
Is there a more elegant way of solving my problem than setting up a complete normal table without PHP/SQL, where I'd have to put in every bit of data about Name,Price and Duration manually?
<table class="table table-bordered table-hover tablesorter row sortable">
<thead>
<tr>
<th class="header">Name</th>
<th class="hidden-xs">Info</th>
<th>Price (in Euro)</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
<?php
//Connect to Database
$db=mysql_connect ("xxxx", "xxxx", "xxxx") or die ('Oops! Da hat wohl' . mysqli_error(). 'Mist gebaut');
//Choose Database
$mydb=mysql_select_db("massageke_de");
//Query Database
$sql="SELECT * FROM Angebote";
//-run the query against the mysql query function
$result=mysql_query($sql);
//Show Results
while($row=mysql_fetch_array($result)){
//Start table ?>
<tr>
<td class="col-sm-2"><?php echo $Name =$row['Name'] ; ?></td>
<!--In this <td>-tag I want to put long textes with links-->
<td class="hidden-xs col-sm-5">echo $Name =$row['Info'];?<</td>
<td class="col-sm-2"><?php echo $Preis =$row['Preis']; ?></td>
<td ckass="col-sm-1"><?php echo $Dauer =$row['Dauer']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
Thanks in advance for helping.
Don't bother asking me additional questions.
P.S.: I hope you can help, without needing the CSS of Bootstrap, that I used.
P.P.S.:I know that my PHP-Script is not protected against PHP-Injection
(but I want to and will learn how to secure it)
Edit: As Jester asked for it. I made it quickly with photoshop because I think an image can express much better, what I want to achieve, than my poorly coding-skills.
Get to the image
Seems to me like the easiest way would be to just edit the info column in the database for each? If you want to do it in php i'd suggest making an array using the names (ids would be better but it seems you don't have access to those?) as keys:
$info['Aroma Teilkoerper'] = "Text about aroma teilkoerper";
$info['Aroma Ganzkoerper'] = "Text about aroma ganzkoerper";
and so on until you have all. Then in the loop:
//Show Results
while($row=mysql_fetch_array($result)){
//Start table ?>
<tr>
<td class="col-sm-2"><?php echo $Name =$row['Name'] ; ?></td>
<!--In this <td>-tag I want to put long textes with links-->
<td class="hidden-xs col-sm-5">echo $Name =$info[$row['Name']];?></td>
<td class="col-sm-2"><?php echo $Preis =$row['Preis']; ?></td>
<td ckass="col-sm-1"><?php echo $Dauer =$row['Dauer']; ?></td>
</tr>
<?php } ?>
Hoping that is a workable solution for you? (also you had a syntax error in your closing php tag.
echo $Name =$row['Info'];?< // <----- should be ?> of course

How to send HTML (<table>) code through $_GET variable

EDIT: I solved my problem in total differnt way, thanks to those who respond anyways! helped a lot!
I need to send a table on HTML through a get variable.
The code is:
<html>
<head>
<meta charset="utf-8" />
<title>Itinerario</title>
<link rel="stylesheet" type="text/css" href="itine.css"/>
</head>
<body bgcolor="#FFC334" link="black" vlink="black" alink="white">
<?php
$html='
<font face="arial">
<center>
<table bgcolor="#F3F3F3" style="border:2px solid black;" cellpadding="10" cellspacing="10">
<tr>
<td></td>
<td>CELL 1</td>
<td>CELL 2</td>
</tr>
</table>
</center>
</font>
';
echo $html;
echo 'LINK ME';
?>
</body>
</html>
The other part its just a $_get:
<?php
$variable = $_GET['itine'];
?>
If I replace the $html in the URL for text it works fine but adding table structure sends nothing (no error), only blank.
Any ideas?
You wouldn't be able to send such complex HTML via GET, especially unescaped.
If you must pass HTML from page to page, you could base64_encode() the HTML, and probably gzcompress() it too. This would help prevent hitting the character limit for GET requests, but wouldn't eliminate the problem for very large tables.
I did once have to do something similar, which required passing a lot of data into GET variables. I had to create a couple of functions to make them GET friendly though:
function shrink($str) {
$str=strtr(base64_encode(addslashes(gzcompress($str,9))), '+/=', '-_,');
return $str;
}
function unshrink($str) {
$str = gzuncompress(stripslashes(base64_decode(strtr($str, '-_,', '+/='))));
return $str;
}
The shrink() function there gzips the string at compression level 9, and removes any characters from the encoded output that could cause issues for GET requests.
unshrink() does the opposite.
If you were to include those functions, you could do something like this in your example:
$html='
<font face="arial">
<center>
<table bgcolor="#F3F3F3" style="border:2px solid black;" cellpadding="10" cellspacing="10">
<tr>
<td></td>
<td>CELL 1</td>
<td>CELL 2</td>
</tr>
</table>
</center>
</font>
';
echo $html;
echo 'LINK ME';
Then to de-compress at the other end:
echo unshrink($_GET['itine']);
This was my first actual post here, so I hope it offers some help!
urlencode(), and no need to decode them, because when they are assigned to $_GET or $_POST they should already have been decoded.
The first problem is that you have a double quote in the HTML you want to send, this closes off the double quote of your a href.
Secondly, you might bump in the limitation of GET requests, theoretically they can only be 256 characters long.
Lastly, I would propose to you to urlencode/decode the data you try to send trough the url:
Encode:
echo 'LINK ME';
Decode:
<?php
$variable = urldecode($_GET['itine']);
?>
Well since you have some limitations about string length on $_GET, it's preferable not to do this. If you explain better what you need, maybe we can provide you another solution.

Correct syntax using JS 'onclick' functions inside PHP echo statements AND with embedded XML fetching

I am likely to get b'*ch slapped because I haven't searched the forum enough before posting, but I really think I searched all relevant posts already, many seem not specifically covering the question I have, the others fly right over my beginner's head ( as I am new to PHP & js ). That being said...
I have built a PHP code to fetch data from an XML file using the $xml=simplexml_load_file();
No worries there, however one of the needed data 'entries' or 'fields' needs to exist within an onclick and/or an onmouseup javascript function.
The code is as follows:
<?php
$xml=simplexml_load_file('prod_test_feed_sameday.xml');
$max = 8;
$i = 1;
foreach($xml->product as $feed){
if ($i <= $max){
echo "<table id='{$feed->position}' class='prod_container'>
<td class='hidden_mask' id='{$feed->position}'>
</td>
<td class='hidden_image' id='{$feed->position}'><span style='background:url({$feed->prod_image_large}) no-repeat center;'/></span><div><a onmouseup='$('.hidden_image#{$feed->position}').slideToggle('slow');' onclick='$('.hidden_mask#{$feed->position}').hide();'><b>CLOSE</b></a></div>
</td>
<tr>
<td class='prod_image' id='{$feed->position}'>
<span style='background:url({$feed->prod_image_small}) no-repeat center; background-size:contain;'/></span>
</td>
<td rowspan='1' class='info_toggle' id='{$feed->position}'><a onmouseup='$('.hidden_image#{$feed->position}').slideToggle('slow');' onclick='$('.hidden_mask#{$feed->position}').show();><img src='images/zoom_02.png' title='See a larger image of these flowers' /></a>
</td>
</tr>
<tr>
<td colspan='2' class='prod_name' id='{$feed->position}'>{$feed->prod_name}
</td>
</tr>
<tr>
<td colspan='2' class='prod_price' id='{$feed->position}'><span id='{$feed->position}'>from: £{$feed->price}</span><a href='{$feed->prod_link}' target='_blank'><span class='buy_button'> Buy it now! </span></a></td>
</tr>
</table>";
$i++;
}
}
?>
The data and the CSS all work perfectly. There is a href link towards the end of the code, which also works perfectly.
I am racking my brain trying to find the error in my syntax within the onlick function.
I have tried all manners of backslashing, using trial and error, for exampel:
onclick='$(\'.hidden_mask#{$feed->position}\').hide();' or
onclick='\'$('.hidden_mask#{$feed->position}').hide();\'' or
onclick=\''$(\'.hidden_mask#{$feed->position}\').hide();\'' or even
onclick=\''$(\\'.hidden_mask#{$feed->position}\\').hide();\'' <--Freddy Krugar 'slashing' example
At any rate I am at a loss.
Try with double quotes and escape them:
echo " ...
onclick=\"$('.hidden_mask#{$feed->position}').hide();\"
...";
Or
echo " ...
onclick='$(\".hidden_mask#{$feed->position}\").hide();'
...";
DEMO
This way you do the escaping in the PHP only, without needing the Freddy Krugar escaping for the DOM parser.

Separating PHP code from HTML output

Very often I have heard people suggesting (and I have done it myself too a few times) to keep things separate: PHP code here, HTML there, external CSS, external JS and so on and so on.
Aside from the obvious readibility and maintenance advantages of doing this are there other strong advantages (e.g. in terms of server load or page processing time) in doing it?
As a trivial example, say we want to implement a table containing some products we read from a DB.
The output we want would be something like
<div class="description">This table lists all our products</div>
<table class="products">
<tr>
<th>Name</th>
<th>Available</th>
<th>Price</th>
</tr>
<tr>
<td>Prod 1</td>
<td>Yes</td>
<td>$100</td>
</tr>
...
...
</table>
<div class="info">Some generic info on the products here</div>
So here we have some static output (the 2 div elements and the table header) and some dynamic output (the actual table content).
We could leave all the static things out of PHP tags and try to keep PHP only where needed
<div class="description">This table lists all our products</div>
<table class="products">
<tr>
<th>Name</th>
<th>Available</th>
<th>Price</th>
</tr>
<?
for ($p=0; $p<count($products); $p++)
{
echo '<tr>';
echo '<td>'.$products[$p]["name"].'</td>';
echo '<td>'.$products[$p]["availability"].'</td>';
echo '<td>'.$products[$p]["price"].'</td>';
echo '</tr>';
}
?>
</table>
<div>.....</div>
On the other hand we could embed everything in PHP
<?
echo '<div class="description">This table lists all our products</div>';
echo '<table class="products"><tr><th>Name</th>'.
'<th>Available</th><th>Price</th></tr>';
for ($p=0; $p<count($products); $p++)
{
echo '<tr>';
echo '<td>'.$products[$p]["name"].'</td>';
echo '<td>'.$products[$p]["availability"].'</td>';
echo '<td>'.$products[$p]["price"].'</td>';
echo '</tr>';
}
echo '</table>';
echo '<div>.....</div>';
What are the reasons to choose one over the other?
The alternative syntax for control structures seems to be more readable to me:
<div class="description">This table lists all our products</div>
<table class="products">
<tr>
<th>Name</th>
<th>Available</th>
<th>Price</th>
</tr>
<?php foreach($products as $p): ?>
<tr>
<td><?php echo $p["name"]; ?></td>
<td><?php echo $p["availability"]; ?></td>
<td><?php echo $p["price"]; ?></td>
</tr>
<?php endforeach; ?>
</table>
<div class="info"><?php echo $info; ?></div>
If its just a piece of code for you to play with, it doesn't really matter at all.
But if an application grows more and more complex (and more people work in it), it will usually come to a point where it is vital to separate the view layer (here: HTML) from the code layer (here: PHP) - so you can assign designers to play around with the output and coders to play around with the functionality behind it.
This ain't a php-only topic, this is very general. Architectural models like MVC are based on similar theories.
I think that it is a very compact string <?= $var ?>
I do not suggest to use short sytax of php. Sometimes it can be problem to move code from one server to another.
Reason you need to do so is time. Nice code is simple to support and upgrade. In some cases it is performance issue also, but not in your case.
Ideal example in your case is:
You have to files
index.php
products.php
File products.php contain
<?php
...
foreach($products as $product)
{
$productHTML[] = '<tr><td>' . $product["name"] . '</td></tr>';
}
$productHTML = implode("", productHTML);
?>
index.php:
<html>
...
<?php echo $productsHTML;?>
...
</html>
Ofcourse more advence developers use more hard constructions, we use functions, class, template idea and etc. But such way is enough for small project.

Categories