I am not going to argue about the choice of a template engine against only PHP. I choose not to use a template engine, like Smarty, because I would like to learn how to properly design a template using PHP and HTML. Could someone provide links or examples on how to design a template page?
Just use alternative PHP syntax for if/for/foreach control language constructs which are designed specifically for this purpose:
<h1>Users</h1>
<?php if(count($users) > 0): ?>
<table>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user): ?>
<tr>
<td><?php echo htmlentities($user->Id); ?></td>
<td><?php echo htmlentities($user->FirstName); ?></td>
<td><?php echo htmlentities($user->LastName); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p>No users in the database.</p>
<?php endif; ?>
I also suggest creating view helpers for HTML outputs that are very similar and use them instead of having repeated HTML code.
It's really not all that difficult.
Non-PHP goes out here
<?php # PHP goes in here ?>
More non-PHP goes out here
<?php # More PHP goes in here ?>
function returnView($filename,$variables){
ob_start();
$htmlfile = file_get_contents($filename);
foreach($variables as $key=>$value){
$htmlfile = str_replace("#".$key."#", $value, $htmlfile);
}
echo $htmlfile;
return ob_get_clean();
}
//htmlfile
<html>
<title>#title#</title>
</html>
//usage
echo returnView('file.html',array('title'=>'hello world!');
im my framework i have function that loads view, and then outs it in layout:
public function returnView(){
ob_start();
$this->loader();
$this->template->show($this->controller,$this->action);
return ob_get_clean();
}
Layout looks like this:
<html>
<head>
<title><?php echo $this->layout('title'); ?></title>
</head>
<body>
<?php echo $this->layout('content'); ?>
</body>
</html>
What you might want to consider, if you should opt for a MVC-style approach, if you include your templates inside an object (one of its class methods) then $this inside the template file will point to the object you called it from.
This can be very useful if you want to ensure some kind of encapsulation for your templates, i.e. if you do not want to rely on global variables to pass around dynamic data (e.g. from a database).
I've used various template engines, and designed my own as well, getting more elaborate over time. I think its best to keep it as simple as possible by using native php stuff, instead of creating elaborate functions. (this article has some good points: Boring Architecture is Good). What I found was much better readability and maintenance when coming back to a project after months or years.
For example:
<?
$name="john";
$email="john#xyz.com";
require "templates/unsubscribe.php";
-- templates/unsubscribe.php --
<?
$o=<<<EOHTML
Hi $name, sorry to see you go.<BR>
<input type=input name=email value=$email>
<input type=submit value='Unsubscribe'>
EOHTML;
echo $o;
Using Richard's example, but more simple:
<h1>Users</h1>
<? if(count($users) > 0): ?>
<table>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<? foreach($users as $user): ?>
<tr>
<td><?= htmlentities($user->Id) ?></td>
<td><?= htmlentities($user->FirstName) ?></td>
<td><?= htmlentities($user->LastName) ?></td>
</tr>
<? endforeach ?>
</tbody>
</table>
<? else: ?>
<p>No users in the database.</p>
<? endif ?>
Related
I'm trying to display an html table in which I'd like to show some php variables.
My code is the following:
<?php
$title = the_title();
?>
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo $title?></td>
</tr>
</tbody>
</table>
In the output I can see the word "Name" as expected but it doesn't print the $title variable (there is a empty space instead).
I've already read some of the questions on the site but they doesn't help me because they suggest to write the same code that I wrote.
I am calling an SQL statement which selects everything from a view. There might be some null values returned, I would like to find them and highlight them in the HTML document. This is my code so far.
How can I find the empty columns (which can be seen in the picture) so I could highlight them with CSS?
Thanks.
<?php
require_once '../includes/header.php';
$sql = $conn->prepare("SELECT * FROM vw_allpropertiesandagents ORDER BY Price");
$sql->execute();
?>
<section class="main-sec">
<h1>All Agents and All properties</h1>
<p>The properties even the ones that have no agents assigned to them are displayed</p>
<table class ='dba-table'>
<tr>
<th>Property Id</th>
<th>Full Address</th>
<th>Price</th>
<th>Property Agent Id</th>
<th>Agent Id</th>
<th>For</th>
<th>Property Type</th>
</tr>
<?php while ($row = $sql->fetch()){ ?>
<tr>
<?php
foreach ($row as $value){ ?>
<td><?php echo $value?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
</section>
<?php
require_once '../includes/footer.php';
?>
This is the HTML output]1
If I understand correctly you are looking for something like this:
<?php foreach ($row as $value): ?>
<?php if($value === null): ?>
<td style="background-color: red;">Empty</td>
<?php else: ?>
<td><?= $value ?></td>
<?php endif; ?>
<?php endforeach; ?>
Please be aware that this code is vulnerable to XSS because you are not escaping the data when echo'ing. I would recommend to only use this code locally for learning purposes.
There are some excellent articles on the internet, which you can read to learn how to prevent XSS injection.
I'm new in this language. I'm working on a website. I use HTML file like this:
<html lang="en">
...
<div class="" id="temperatura" name="temp">
<?php require 'php/staticsTemp.php'; ?>
<h3 class="centered">Temperature</h3>
<hr>
<br>
<table class="tg" border="5">
<tr>
<th class="tg-031e">Temperature ºC</th>
<th class="tg-031e">Date & Time</th>
</tr>
<tr>
<td class="tg-031e">33</td>
<td class="tg-031e">44</td>
</tr>
</table>
</div>
...
</html>
And I want to substitute the value 33 and 44 in the table to values that are inside the PHP file.
My PHP looks like this:
<?php
include("ligacaobd.php");
$sql="SELECT * FROM Valores ORDER BY Momento DESC LIMIT 20";
$result = mysql_query($sql, $ligacaobd) or die(mysql_error());
$rowValor = mysql_fetch_assoc($result);
do
{
$data[date('d/m/Y H:i:s', $rowValor['Momento'])]=$rowValor['Temperatura'];
}
while ($rowValor= mysql_fetch_assoc($result));
?>
Any thoughts? I tried with function POST, but in HTML doesn't work.
You must convert your html in .php as it is and include this php code, either directly in the page or via another php page.
You will then be able to manipulate your variables and do something such as:
<td class="tg-031e"><?php echo $myVariable1; ?></td>
<td class="tg-031e"><?php echo $myVariable2; ?></td>
I'm not quite certain what you mean, but I will try to help you.
First of all don't* use mysql functions anymore. These functions are no longer maintained. Use **mysqli or PDO instead.
If you want to show variables in a HTML document you can do the following thing.
<tr>
<td class="tg-031e"><?php echo $var1; ?></td>
<td class="tg-031e"><?php echo $var2; ?></td>
</tr>
Also I would recommend you separating your HTML files from the PHP or at least place your PHP code at the top of your document. For example:
<?php
$var1 = 'Example Variable';
?>
<html lang="en">
<head>
<title>Example</title>
</head>
<body>
<?php echo $var1; ?>
</body>
<html>
Yet the best practice is separating HTML from PHP.
Since you are new to the PHP language, I have some great tutorials for you.
Take a look at http://www.w3schools.com. They have some basic PHP tutorials for you to start with.
Good luck.
Don't use mysql_* functions anymore! They are deprecated in PHP 5.5 and should be removed in 5.6. Use PDO instead.
Not tested yet, but should work. You just need to change your <table /> code to this:
<table class="tg" border="5">
<tr>
<th class="tg-031e">Temperature ºC</th>
<th class="tg-031e">Date & Time</th>
</tr>
<?php foreach ($data as $datetime => $temperature): ?>
<tr>
<td class="tg-031e"><?php echo $temperature; ?></td>
<td class="tg-031e"><?php echo $datetime; ?></td>
</tr>
<?php endforeach; ?>
</table>
Hope it helps :)
what would be the proper implementation of displaying an empty/blank table or just the table header if query result is empty?
**note/conditions
no page redirection
no creation of two tables, one for query with empty result and one for query with results
or is there a much, much better way to do this?
here is a sample code:
<?php if(isset($result)){ ?>
<table>
<tr>
<td>Name</td>
<td>Email</td>
</tr>
<?php foreach($result as $key => $data){?>
<tr>
<td><?php echo $data['name'];?></td>
<td><?php echo $data['email_add'];?></td>
</tr>
<?php }?>
</table>
<?php } ?>
the problem here is that it still throws an error on foreach loop.
When the query result returns false return an empty array instead
I hope this help , and ready for more help if needed
About the exception:
You check if $results is set, but then you try to loop over $result (without a trailing s). I believe you have a typo, which might be a part of the problem. Fixing the typo and making sure that the result is not empty (it might be set, but still empty) will probably fix the exception being thrown.
About always showing the header:
To display the header no matter what, move the if-statement to just before the the loop.
FYI - About well formatted HTML-tables:
To declare a header on a table, you usually make use of the <thead> element - to separate it from the content of the table. An example of a well-formatted HTML-table:
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>john#email.com</td>
</tr>
</tbody>
</table>
More on formatting tables
In your case, I would put the loop around the <tr> element within the <tbody>.
<?php if(isset($result) && !empty($result)): ?>
<table>
<tr>
<td>Name</td>
<td>Email</td>
</tr>
<?php foreach($result as $data): ?>
<tr>
<td><?php echo $data['name'];?></td>
<td><?php echo $data['email_add'];?></td>
</tr>
<?php endforeach ?>
</table>
<?php else: ?>
No results found.
<?php endif ?>
Note that I prefer to use the long-form of statements for PHP templates, as it greatly improves readability.
If the array is not null (and has values in it), then I want to display the table.
But if it is null, then I don't want to display any table code at all.
Using an MVC framework which appends a footer to the page.
What is the best way to avoid a statement like:
<?php
if ($users) {
echo '<table id="tha_table" cellpadding="0" cellspacing="0" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>';
} ?>
And, don't want to do another test to add the table footer.
I think I see what you are after...
I would place all of the HTML in a separate file, and conditionally include it.
if(!empty($users)) {
include "users_table.template";
}
Note that the template file can include php if you want it to.
I always use empty() to check whether an array is empty. Empty will also check whether the variable is null. Note that empty() does not throw a warning if the array variable is not set, which may or may not be desirable.
<?php
$displayUserTable = !empty($users);
?>
<?php if($displayUserTable): ?>
<table id="tha_table" cellpadding="0" cellspacing="0" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user): ?>
<tr>
<td><?php echo htmlspecialchars($user['firstName']); ?></td>
<td><?php echo htmlspecialchars($user['lastName']); ?></td>
<td><?php echo htmlspecialchars($user['emailAddress']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<?php if($displayUserTable): ?>
<!-- show footer here... -->
<?php endif; ?>
I recommend you use either a templating system or any other vehicle to separate your PHP code from the HTML rendering.
All template systems I know of allow for a block to be skipped depending on a boolean, so you would just include the (template for the) table in your page template and surround it with whatever your chosen framework uses as an if or repeat n times construct.