Integrating PHP files into HTML files - php

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 :)

Related

How to exclude HTML from PHP and PHP file still able to link with the HTML file?

View table<-- this is my example. And code is provided too. I need to separate HTML from PHP, moving HTML to another file but my PHP code still be able to link with it. Is there any idea? I am trying to make something like View model controller.
<html>
<head>
<meta charset="utf-8">
<title>View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>
Dashboard
| View Records
| Add Admin
| Logout
</p>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>ID</strong></th>
<th><strong>Username</strong></th>
<th><strong>User Password</strong></th>
<th><strong>Full Name</strong></th>
<th><strong>Edit</strong></th>
<th><strong>Delete</strong></th>
</tr>
</thead>
</body>
<?php
$count=1;
$sel_query="Select * from admin ORDER BY id ASC;";
$result = mysqli_query($con,$sel_query);
while($row = mysqli_fetch_assoc($result)) { ?>
<tr>
<td align="center"><?php echo $row["ID"]; ?></td>
<td align="center"><?php echo $row["username"]; ?></td>
<td align="center"><?php echo $row["user_pass"]; ?></td>
<td align="center"><?php echo $row["fullname"]; ?></td>
<td align="center">
Edit</td>
<td align="center">
Delete</td>
</tr>
<?php $count++; } ?>
</tbody>
</table>
</div>
</body>
</html>```
Separating the php and html is a good start, and helps you see the next step in converting to OOP and then MVC.
MVC at this point is too broad for a simple answer here, but I would recommend this as a first step as it has the underlying principles:
PHP is always at the top; never output anything until all your logic is finished
Load configuration
Work with user input and redirect if POST
Execute business logic
Exit PHP and output HTML. Remember, PHP is essentially a templating language, might as well use it as such
Your code would then look something like this:
<?php
// load database connection, etc
$url = 'your url';
// deal with user input. Always use POST if data will be changed!
if($_POST['action'] == 'delete') {
// delete from admin where id=?
header('location: '.$url);
die;
}
// end "controller" section
// begin "model" section
$sel_query="Select * from admin ORDER BY id ASC;";
$result = mysqli_query($con,$sel_query);
// end "model" section
// begin "view" section.
// Note, you could simply put the html in a separate file and just include it here.
?>
<html>
<head>
<meta charset="utf-8">
<title>View Records</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="form">
<p>
Dashboard
| View Records
| Add Admin
| Logout
</p>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>ID</strong></th>
<th><strong>Username</strong></th>
<th><strong>User Password</strong></th>
<th><strong>Full Name</strong></th>
<th><strong>Edit</strong></th>
<th><strong>Delete</strong></th>
</tr>
</thead>
</tbody>
<?php while($row = mysqli_fetch_assoc($result)): ?>
<tr>
<td align="center"><?= $row["ID"] ?></td>
<td align="center"><?= $row["username"] ?></td>
<td align="center"><?= $row["user_pass"] ?></td>
<td align="center"><?= $row["fullname"] ?></td>
<td align="center">
<form method="post">
<input type="hidden" name="action" value="delete" />
<input type="hidden" name="id" value="<?= $row["ID"] ?>" />
<input type="submit" value="Delete" />
</form>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
</body>
</html>
Notice that following this pattern is laying the groundwork for moving to mvc. But first, start working on your oop chops and move all the business logic into a model object.
After that, you can move the template to its own file, and have the model injected into the view, which lets the view have access to the info it needs, and then render the output.
Meanwhile, you'll need a router (all traffic is rerouted to index.php) and controller, and figure out which interpretation of MVC you will use ;)
Here's a very basic solution.
Make an HTML file as a template. E.g. "template.html". Use HTML comments as placeholders for the data. (I went with comments as it means the HTML remains compliant)
I've left out some of the non-relevant bits, so hopefully you get the idea:
<html>
...
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>ID</strong></th>
<th><strong>Username</strong></th>
<th><strong>User Password</strong></th>
<th><strong>Full Name</strong></th>
<th><strong>Edit</strong></th>
<th><strong>Delete</strong></th>
</tr>
</thead>
<tbody>
<!--ROW-->
<tr>
<td align="center"><!--ID--></td>
<td align="center"><!--username--></td>
<td align="center"><!--user_pass--></td>
<td align="center"><!--fullname--></td>
<td align="center">
Edit</td>
<td align="center">
Delete</td>
</tr>
<!--ENDROW-->
</tbody>
</table>
</div>
</body>
</html>
Then, in your PHP code, you read in the html, find the row template, and replace the fields as needed:
<?php
// Read the template
$html = file_get_contents('template.html');
// Find the row template
$regRowTemplate = '/<!--ROW-->(.*)<!--ENDROW-->/i';
preg_match($regRowTemplate, $html, $m);
$rowTemplate = $m[1];
// Start building our replacement rows
$htmlRows = '';
$count=1;
$sel_query="Select * from admin ORDER BY id ASC;";
$result = mysqli_query($con,$sel_query);
while ($row = mysqli_fetch_assoc($result)) {
// Start with a fresh copy of the template
$htmlRow = $rowTemplate;
// Replace comment placeholders with values
foreach ($row as $key => $value) {
$htmlRow .= str_replace('<!--' . $key . '-->', $value, $htmlRow);
}
// Append to our rows
$htmlRows .= $htmlRow;
$count++;
}
// Replace the row template with our expanded rows
$html = preg_replace(regRowTemplate, $htmlRows, $html);
// Do something with the html
Source untested, but should give you a good starting point. I kept it pretty raw. If I was doing this for real, I'd allow for the possibility of spaces in the comment placeholders by using a regular expression instead, but for now it's good enough.

How use session variable in sql using php

I have a problem with displaying files added by the logged user.
I do not know how to pass the variable correctly to the sql query.
Can anyone help me with this?
Currently, the code looks like this:
<?php
include_once 'dbconnect.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>File Uploading With PHP and MySql</label>
</div>
<div id="body">
<table width="80%" border="1">
<tr>
<th colspan="4">your uploads...<label>upload new files...</label></th>
</tr>
<tr>
<td>File Name</td>
<td>File Type</td>
<td>File Size(KB)</td>
<td>View</td>
</tr>
<?php
$sql="SELECT * FROM files";
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set))
{
?>
<tr>
<td><?php echo $row['file'] ?></td>
<td><?php echo $row['type'] ?></td>
<td><?php echo $row['size'] ?></td>
<td>view file</td>
</tr>
<?php
}
?>
</table>
</div>
</body>
</html>
I am trying to change this record :
$sql="SELECT * FROM files";
to
$sql="SELECT file, type, size FROM files WHERE userId ='$_SESSION[userId]'";
but I still do not get the correct result. Can anyone help?
It looks like the issue with that line is in how you are including the $_SESSION variable. You should have quotes around userId like $_SESSION['userId'] or {$_SESSION['userId']}.
More importantly you should avoid entering variables directly into MySQL queries. I would recommend using MySQLi or PDO instead of MySQL, and look into prepared statements (here or here, for example).

Echo HTML with PHP in the middle

I am new to PHP and am running into a small problem with this code. I am trying to make a layout for a page that uses more PHP to fill in the blanks.
When I view the source <? include $navbar ?> is commented out but <?=$pagetitle?> works, why is that?
For reference:
$navbar = "navbar.php";
and navbar.php:
<?php echo "Select Car Change Profile"; ?>
Layout.php:
<?php
echo "
<html>
<head>
<title>Race Data. <?=$pagetitle?></title>
</head>
<body>
<div id='page'>
<table border='1'>
<tbody>
<tr>
<td colspan='3'>Banner goes here.<?=$pagetitle?></td>
</tr>
<tr>
<td rowspan='2'>Left menu</td>
<td colspan='2'><? include $navbar; ?></td>
</tr>
<tr>
<td>Content</td>
<td>Right menu</td>
</tr>
<tr>
<td colspan='3'>Footer</td>
</tr>
</tbody>
</table>
</div>
</html>
";
?>
I'm sure knowing this will help amny future problems I run into.
Also, what are the diferences in using <? ?> vs <?php ?>?
In php, you always need to use <?php /*code*/ ?>
The shorthand version to echo something is <?= /*string*/ ?>, but to run code, such as an include you would need to start with <?php. In your example, this would be:
<tr>
<td rowspan='2'>Left menu</td>
<td colspan='2'><?php include $navbar; ?></td>
</tr>
Correction
I only just noticed that you placed the PHP tags inside another set of PHP tags. You're kind of doing it the hard way. In a PHP file, anything is regarded as an echo, except for content inside <?php ?> tags. So this should work perfectly for you:
<html>
<head>
<title>Race Data. <?=$pagetitle?></title>
</head>
<body>
<div id='page'>
<table border='1'>
<tbody>
<tr>
<td colspan='3'>Banner goes here.<?=$pagetitle?></td>
</tr>
<tr>
<td rowspan='2'>Left menu</td>
<td colspan='2'><?php include $navbar; ?></td>
</tr>
<tr>
<td>Content</td>
<td>Right menu</td>
</tr>
<tr>
<td colspan='3'>Footer</td>
</tr>
</tbody>
</table>
</div>
</html>
The difference is that I didn't put <?php ?> tags around the whole thing.
Try
short_open_tag=On;
in php.ini
And restart your Apache server.

Why is there no output in the given PHP file

I am trying to calculate ( by a PHP file ) the diameter, area and circumference of a circle whose radius is given by the user in a html file. User gives the values of the radius and PHP script calculates the above mentioned quantities. The problem is that when I am executing the program, the html takes the input but the PHP script isn't showing the output.
The code is as follows:-
circle.html:-
<html>
<head>
<title>Circle</title>
</head>
<body>
<form method="GET" action="circle1.php">
<center>
<h1>Circle</h1>
<table border= 2 width=200>
<tr align=center>
<td>Radius</td>
<td><input type="text" name=radius size=5></td>
</tr>
<tr align=center>
<td colspan=2>
<input type="submit">
<input type="reset">
</td>
</tr>
</table>
</center>
</form>
</body>
</html>
circle1.php:-
<html>
<head>
<title>Circle</title>
</head>
<body>
<center>
<h1>Circle</h1>
<?php
define("PI",3.14159,TRUE);
GLOBAL $d,$c,$a,$r;
$r=$_GET['radius'];
$d=2*$r;
$c=2*PI*$r;
$a=PI*$r*$r;
?>
<table border = 2 width=200>
<tr>
<td>Diameter</td>
<td><?php echo $d; ?></td>
</tr>
<tr>
<td>Circumference</td>
<td><?php echo $c; ?></td>
</tr>
<tr>
<td>Area</td>
<td><?php echo $a; ?></td>
</tr>
</table>
<h2>Back</h2>
</center>
</form>
</body>
</html>
sorry for such a long post. Any help would be appreciated.
Some server setups such as various Amazon Linux AMIs require you to output HTML through php print functions such as echo to properly execute. If you have this type of setup, then you'll need to execute your server-side PHP code before you output all your client-side HTML.
Try this for circle1.php:
<?php
define("PI",3.14159,TRUE);
GLOBAL $d,$c,$a,$r;
$r=$_GET['radius'];
$d=2*$r;
$c=2*PI*$r;
$a=PI*$r*$r;
echo'
<html>
<head>
<title>Circle</title>
</head>
<body>
<center>
<h1>Circle</h1>
<table border="2" width="200">
<tr>
<td>Diameter</td>
<td>'.$d.'</td>
</tr>
<tr>
<td>Circumference</td>
<td>'.$c.'</td>
</tr>
<tr>
<td>Area</td>
<td>'.$a.'</td>
</tr>
</table>
<h2>Back</h2>
</center>
</form>
</body>
</html>';
?>
Your code could be cleaned up a bit, but it should work. There isn't anything intrinsically wrong with it. I literally cut and pasted it as a test and it works fine.
If the first page (pure HTML) works, but you get nothing for the second (circle1.php) then the first thing to check is if your webserver is configured to use PHP and if the path to the php.ini is accurate because the bottom line is that your PHP parser is out of the loop.
Your code is correct. You must have some problem related to php.ini or apache . Check weather your <?php code is escaping or not by checking source code. . If it is , put this code on the top error_reporting(E_ALL); and try to debug it.
You need to encapsulate your input properties with quotes.
Replace
<input type="text" name=radius size=5>
With
<input type="text" name="radius" size="5">

Using PHP as a template engine

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 ?>

Categories