PHP HTML Template with Loop capabilities - php

I would like to ask some help and ideas on how to implement a loop inside the template. I can do foearch below but how can i include it to the template and show it in the results.
foreach($results as $row) {
$name = $row['name'];
$address = $row['address'];
}
What i want to achieve the results is something like below and how do I put the $template->publish(); in a variable so I can use it to store that data to the DB. thanks a lot.
<html>
<head>
<title>My Template Class</title>
</head>
<body>
<table><tr>
<td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>Name goes here</p>
<p>Address goes here </p>
</td>
<td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>Name goes here</p>
<p>Address goes here </p>
</td>
<td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>Name goes here</p>
<p>Address goes here </p>
</td>
</tr>
</table>
</body>
</html>
The template class
<?
class Template {
public $template;
function load($filepath) {
$this->template = file_get_contents($filepath);
}
function replace($var, $content) {
$this->template = str_replace("#$var#", $content, $this->template);
}
function publish() {
eval("?>".$this->template."<?");
}
}
?>
The template design.html
<html>
<head>
<title>#title#</title>
</head>
<body>
<h3>Hello #name#!</h3>
<p>The time is: #datetime#</p>
<? echo "<p>Embedded PHP works too!</p>"; ?>
</body>
</html>
the index.php
<?
include "template.class.php";
$template = new Template;
$template->load("design.html");
$template->replace("title", "My Template Class");
$template->replace("name", "William");
$template->replace("datetime", date("m/d/y"));
$template->publish();
?>

PHP itself is as good at templates as any other engine.
No need anything else
$pagetitle = "My Template Class";
foreach($results as $row) {
$row['date'] = date("m/d/y");
$data[] = $row;
}
$data = chunk_split($data,3);
Then in template
<html>
<head>
<title><?=$pagetitle?></title>
</head>
<body>
<table>
<?php foreach ($data as $chunk): ?>
<tr>
<?php foreach ($chunk as $row): ?>
<td>
<h3>Hello <?=$name?>!</h3>
<p>The time is: <?=$date?></p>
<p>Embedded PHP works in the template</p>
<p><b>But embed PHP in the data is a VERY BAD IDEA</b></p>
<p><?=$address?></p>
</td>
<?php endforeach ?>
</tr>
<?php endforeach ?>
</table>
</body>
</html>
I made your example a bit more complicated yet closer to the real life.
It will print your table in the rows by 3 columns in each

Just don't re-invent the wheel, PHP works wonderfully as a templating language:
The template class
<?
class Template
{
private $template;
private $vars;
function load($filepath) {
$this->template = $filepath;
}
function replace($var, $content)
{
$this->vars[$var] = $content;
}
function publish()
{
extract($this->vars);
include($this->template);
}
}
?>
The template design.phtml
<html>
<head>
<title><?php echo $title ?></title>
</head>
<body>
<?php foreach($rows as $row) { extract($row); ?>
<h3>Hello <?php echo $name; ?></h3>
<p>The time is: <?php echo $datetime; ?></p>
<?php echo "<p>Embedded PHP works too!</p>"; ?>
<?php } ?>
</body>
</html>
The use is pretty much the same, just assign more than one row to make use of it:
<?
include "template.class.php";
$template = new Template;
$template->load("design.phtml");
$template->replace("title", "My Template Class");
$rows = array();
$rows[] = array(
"name" => "William",
"datetime" => date("m/d/y"),
);
$template->replace("rows", $rows);
$template->publish();
?>
Hope this is helpful.

Your PHP code:
$htmldata ="";
($results as $row) {
$name = $row['name'];
$address = $row['address'];
$htmldata .="
<tr><td>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
<p>".$name."</p>
<p>".$address." </p>
</td>
</tr>
";
}
Then in your template design.html, you will pass the $htmltable variable and embedd there:
<html>
<head>
<title>#title#</title>
</head>
<body>
<h3>Hello #name#!</h3>
<p>The time is: #datetime#</p>
<? echo "<p>Embedded PHP works too!</p>"; ?>
<table>
<?php echo $htmltable; ?>
</table>
</body>
</html>

Related

Displaying MySQL output in PHP as rows rather than columns

Good afternoon all :)
I would like to display my MySQL output on a PHP page as rows rather than columns for easier mobile viewing and scrolling (so the user can just scroll down the data instead of across).
I'd read about pivots and transposing but wasn't sure what was the most appropriate way to transform the return data output on the webpage. Please can you advise on what is best to use? It looks like it's easier to do it in PHP rather than MySQL?
I'm using a standard post form, connection PDO, isset, thead, php echo td and th etc.
My current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title></title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<h1>Find people</h1>
<form method="post">
<label for="people">Enter person</label>
<input type="text" id="people" name="people">
<input type="submit" name="submit" value="View Results">
</form>
<?php
//error_reporting(-1);
//ini_set('display_errors', 'On');
if (isset($_POST['submit'])) {
try {
require "./config.php";
require "./common.php";
$connection = new PDO($dsn, $username, $password, $options);
$sql = "SELECT *
FROM Basics
WHERE UniqueID = :people";
$people = $_POST['people'];
$statement = $connection->prepare($sql);
$statement->bindParam(':people', $people, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetchAll();
} catch(PDOException $error) {
echo $sql . "<br>" . $error->getMessage();
}
}
?>
<?php
if (isset($_POST['submit'])) {
if ($result && $statement->rowCount() > 0) { ?>
<h2>Results</h2>
<table>
<?php echo '<table border="1">';?>
<thead>
<tr>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
</tr>
</thead>
<tbody>
<?php foreach ($result as $row) { ?>
<tr>
<td><?php echo escape($row["Field 1"]); ?></td>
<td><?php echo escape($row["Field 2"]); ?></td>
<td><?php echo escape($row["Field 3"]); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } else { ?>
<br>No results found for <?php echo escape($_POST['people']); ?>, as the data has likely not been added yet.
<?php }
} ?>
<!--
<?php if (isset($_POST['submit']) && $statement) { ?>
<?php echo escape($_POST['people']); ?> successfully found.
<?php } ?>
-->
</body>
</html>
My current output:
Current example output:
Output example I would like:
Similar to this example I found (can be in a table or not like below):
Update edit:
Looks like I just needed to use ul and li!
<ul>
<li><b>Name:</b> <?php echo escape($row["Name"]); ?></li>
</ul>
I would use array_walk() to loop over the rows and within that loop, start the tr-tag, loop over the values of the current row, output them as td-elements, exit the td-loop, output the closing tr-tag and exit the tr-loop. Not that fancy solution but simple.
Looks like I just needed to use ul and li!
<ul>
<li><b>Name:</b> <?php echo escape($row["Name"]); ?></li>
</ul>

Loading a PHP page into a HTML div

So I am currently trying to create a portion of my website that fetches a mySQL table. I wrote the php to fetch the data, create a table, and print out the table in a separate php file named display.php. Now i am trying to load it into a div on my html page but for some reason it is not working. I am using XAMPP and php is working as my login page works. Here is the code:
HTML: (I have tried both include and require)
<html>
<body>
<div id="display" class="myCustom1">
<?php require('display.php'); ?>
</div>
<div id="display" class="myCustom1">
<?php include("display.php"); ?>
</div>
</body>
</html>
PHP: (if i run just the php page it creates the table)
<?php
$servername = "localhost";
$username = "test";
$password = "test";
$database = "data1";
//create connection & access DB
$connect = mysqli_connect("$servername","$username","$password","$database");
//if error, display error
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($connect,"SELECT * FROM data1enter");
echo
"
<table border='1'>
<tr>
<th>Song</th>
<th>Author</th>
</tr>
";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['song'] . "</td>";
echo "<td>" . $row['author'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($connect);
?>
You are using <?php ?> tags in the html file, Change the extension of the file containing the below code to .php from .html and you will be able to use include function.
<html>
<body>
<div id="display" class="myCustom1">
<?php require('display.php'); ?>
</div>
<div id="display" class="myCustom1">
<?php include("display.php"); ?>
</div>
</body>
</html>
Also make sure the include path is correct.
Hope it helps !
Display should be blade template ..
#include('display')
Give path to display template
Just put the php in a function. Then you can do this:
<html>
<body>
<?php require_once('display.php'); ?>
<div id="display" class="myCustom1">
<?php render(); ?>
</div>
</body>
</html>
<?php
function render()
{
//YOUR PHP CODE
}
?>

PHP - echo doesn't seem to work right

I have this function that gets a table from another site by finding each row of that table and, providing that row isn't a duplicate, echos it to my site. I want to add my own row to the bottom though so I thought it would be as simple as just echoing
<tr><td>TEXT</td></tr>
as you can see below. But when I load the page, this row isn't added. Anyone know what the cause may be?
Here is the website if that helps.
function getStats(){
$page = file_get_html(getPageURL());
$rows = array();
echo "<table id=statsTable>";
foreach($page->find('html/body/div/div[1]/center/table/tbody/tr[1]/td/table/tbody/tr/td[2]/table/tbody/tr/') as $key=>$element) {
if(!in_array($element, $rows)){
$rows[$key]=$element;
echo $rows[$key-1];
}
}
echo "<tr><td>Viewing old updates will be added soon</td></tr></table>";
}
Main problem was in key offset, when you work with arrays it's better to use keys in this case. So in order to that I've changed the in_array to array_key_exists, because we want to check if key exists, but if you want to work with element you have to know its key.
function getStats(){
$page = file_get_html(getPageURL());
$rows = array();
echo "<table id=statsTable>";
foreach($page->find('html/body/div/div[1]/center/table/tbody/tr[1]/td/table/tbody/tr/td[2]/table/tbody/tr/') as $key => $element) {
if(!array_key_exists($key, $rows)){
$rows[$key] = $element;
/* Echo only when it exists */
if(array_key_exists($key-1, $rows)){
echo $rows[$key-1];
}
}
}
echo "<tr><td>Viewing old updates will be added soon</td></tr></table>";
}
?>
<?php
include "getData.php";
include "simple_html_dom.php";
?>
<!DOCTYPE HTML>
<html>
<head>
<title>KSA Flight Tracker</title>
<link rel="stylesheet" type="text/css" href="KSAStyle.css"/>
</head>
<body>
<div id="page">
<div id="leftPanel">
<p id="missionsHeader">Active Missions</p>
<?php getList(); ?>
</div>
<div id="mainPanel">
<p id="infoHeader">
<?php getTitle(); ?>
</p>
<div id="info">
<center>
<?php
getInfo();
getImage();
getMap();
getStats();
?>
</center>
</div>
</div>
</div>
</body>
</html>

Array gets emptied when i try to add new stuff to it (PHP)

I am trying to add stuff into an array after every click a user makes on a category but for some reason it keeps replacing everything in the array. I can't figure out where I am going wrong. I've tried 'googling' it and every example i find looks similar to what i have written. Please Help!
these functions are store in core.php
function getStoreBacktrace($cat) {
include("config.php");
$backtrace = array();
if ($cat != 0) {
array_push($backtrace, $cat);
}
if (count($backtrace != 0)) {
foreach($backtrace as $c){
echo getBackCatName($c);
}
}
print_r($backtrace); // Put this to see what output is
}
function getBackCatName($c) {
include("config.php");
$query = 'SELECT * FROM `home_store_cats` WHERE `id`="'.$c.'"';
$r_query = mysql_query($query);
$result = mysql_fetch_array($r_query);
echo ' > '.$result['name'].'';
}
this function prints out a list of links the user can click on
function getStoreCat($cat) {
include("config.php");
$query = 'SELECT * FROM `home_store_cats` WHERE `main`="'.$cat.'" ORDER BY `name` ASC';
$r_query = mysql_query($query);
echo '<ul>';
while ($result = mysql_fetch_array($r_query)) {
echo '<li>';
echo ''.$result['name'].'';
echo '</li>';
}
echo '</ul>';
}
and it gets called in store.php
<?php
include("config.php");
include("core.php");
$backtrace = array();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title><?php echo getSiteTitle().' :: '.getSiteSlogan(); ?></title>
</head>
<body>
<table width="100%">
<tr>
<td colspan="2">
<!-- Backtrace -->
Home
<?php echo getStoreBacktrace($cat, $backtrace); ?>
</td>
</tr>
<tr>
<td>
<!-- Categories -->
<table>
<tr>
<td><?php echo getStoreCat($cat); ?></td>
</tr>
</table>
</td>
<td>
<!-- Products -->
<table>
<tr>
<?php echo getStoreProducts($cat); ?>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
now everytime a user clicks on a link that is made from the function getStoreCat($cat) it refreshes the page with new links to click on and new products to show depending on what $cat they chose. i want to push the $cat to the $backtrace array.
Right here:
$backtrace = array();
You are effectively resetting the array for each call to getStoreBacktrace().
EDIT:
Thanks for fixing your question. Now it's clear that the issue is you need to make $backtrace persistent through multiple page views. Do this using sessions:
Page template
<?php
session_start(); // enable sessions
include("config.php");
include("core.php");
?>
<!DOCTYPE html>
etc...
Function definition
<?php
function getStoreBacktrace($cat) {
include_once("config.php"); // use include_once() to prevent possible errors
if (!isset($_SESSION['backtrace']))
$_SESSION['backtrace']= array();
if ($cat != 0) {
array_push($_SESSION['backtrace'], $cat);
}
...
Everytime you call getStoreBacktrace you instantiate a brand new array in $backtrace.

Delete PDO OOP Problems

Good day everyone.
I totally need your help.I am pretty new to oop & pdo and I am having problems with my delete function. The item will not be delete whenever I click the delete button. It seems like I can't call the id. I just don't know what to do. Please help me solve this problem.
Here is my code.
For the class(codex):
public function deleteData($id,$table)
{
$q = "DELETE FROM $table WHERE id = :id";
$stmt = $this->con->prepare($q);
$stmt->execute(array(':id'=>$id));
}
For the UI and the page where I call the id:
<?php
include_once "../styles/header-menu-out.php";
include_once "dbconnection.php";
function __autoload($class){
include_once("../main/".$class.".php");}
$code = new codex("localhost","library_books","root","" );
$books = $code->showData("book_info");
if(isset($_REQUEST['id'])){
if($code->deleteData($_REQUEST['id'],"book_info")){
echo "<script type='text/javascript'>
alert('Book Information have been deleted.');
window.location='bookDeleteUI.php';
</script>";
}}
?>
<html>
<head><link rel="stylesheet" type="text/css" href="../styles/library_style.css"></head>
<title>Book-A-Holic: Delete & Update Books</title>
<body><br /><center>
<div id="content"><div class="echoname"><br/><br/><b><h2>Book Settings</h2></b><br/></div>
<table id="tablecolor" class="echoname" border="1">
<td>ID</td>
<td>Title</td>
<td>Author</td>
<td>ISBN</td>
<td>Publisher</td>
<td>Language</td>
<td>Genre</td>
<td>Quantity</td>
<td>Availability</td>
<td>Queue</td>
<td><center>Settings</center></td>
<?php
echo "<pre>";
foreach ($books as $book)
{
echo "<tr>";
extract($book);
echo "<td>".$id."</td>";
echo "<td>".$title."</td>";
echo "<td>".$author."</td>";
echo "<td>".$isbn."</td>";
echo "<td>".$publisher."</td>";
echo "<td>".$language."</td>";
echo "<td>".$genre."</td>";
echo "<td>".$quantity."</td>";
echo "<td>".$availability."</td>";
echo "<td>".$queue."</td>";
?>
<td><button class="btn"><a href="bookUpdateUI.php?update=$id" >Edit</a></button>
<button class="btn">Delete</button></td>
<?php echo "</td>";
}
echo "</pre>";
?>
</table><br />
</div></center>
</body>
</hmtl>
<?php include_once "../styles/footer-admin.php"; ?>
Looks like you've almost got it and well done on using PDO with parametized queries. The problem is that you're not outputting the $id through the php interpreter. You need to do this:
<button class="btn">Delete</button></td>

Categories