How to make a PHP template without a database? - php

I'm working on a small company "brochure" website. I have a few pieces that repeat for example:
Menu
Submenu
Footer
Subheader
Say a page "comparison.php" needs to have all of the above and then content. I could do which is how I started:
<?php include '/partial/menu.php'; ?>
<p>This is a product comparison</p>
<figure>
<figcaption>Probably an image here</figcaption>
((image))
</figure>
<table>
<tr><td>Product 1</td><td>Product 2</td></tr>
<tr><td>Point A</td><td>Point B</td></tr>
</table>
<?php include '/partial/footer.php'; ?>
I'm thinking what a better way might be. Perhaps adding a directory content so then it becomes:
<?php include '/partial/menu.php'; ?>
<?php include '/content/comparison.php'; ?>
<?php include '/partial/footer.php'; ?>
This still feels clunky to me especially when I've got multiple subheaders and submenus depending on the page.
I've read online about templates with PHP but everything is with databases just inserting variables like, Programmers.SE - How to structure template system using plain PHP How would I go about streamlining this as much as possible without using a database? And please do not tell me to use a CMS, it's not an option.

Alright I think I figured out a methodology that is quite nice.
3 Main Files being used:
comparison.php
information_template.php
content/comparison.php
comparison.php
<?php
$pagename = 'comparison';
include('information_template.php');
?>
information_template.php
<?php include '/content/' . $pagename . '.php'; ?>
content/comparison.php
All of the content goes here
Now I can just make a page in my root and a page in the content for each one with the same format and it should work. I'll probably add some additional to comp.php something like $pagetype = 'information'; or $pagetype = 'review'; so I can then add to my information_template.php:
<?php include '/partial/' . $pagetype . '-subheader.php'; ?>
<?php include '/partial/' . $pagetype . '-toc.php'; ?>

Related

How to load an html snippet into page without changing pages

I'm new to PHP (3 days) and I understand the basic concept of using includes for creating high level templates. I'd like to further utilize this tool to load more granular content, but I'm not sure how to approach this. The html below is an example of a page template put together with php includes. If you reference this html, let's say I have a widget on the page contained here: <?php include('include/WIDGET.php'); ?>. In the simplest of scenarios, there would be a link above the widget that reads "Widget 2". On click of this link, I would want the WIDGET.php content to be replaced with widget2.php. How can I manipulate the include to load widget2.php?
HTML
<!-- File: index.php -->
<html>
<head>
<?php include('include/head.php');?>
<title><?php echo $siteName;?></title>
</head>
<body>
<?php include('include/header.php'); ?>
<!-- CONTENT -->
<?php include('include/WIDGET.php'); ?>
<?php include('include/main-content.php'); ?>
<!-- CONTENT END -->
<?php include('include/footer.php'); ?>
</body>
</html>
To change what file(s) is included, you would need to provide some sort of parameter to the page, that can conditionally include the correct widget.
For example, including it in URL query string, such as:
http://yoursite/index.php?content=widget2
Then, in your PHP file, you can get this value:
if (isset($_GET['content']) && !empty($_GET['content'])) {
$widget = $_GET['content'];
} else {
$widget = 'widget';
}
And include it in your HTML:
[...]
<!-- CONTENT -->
<?php include('include/' . $widget . '.php'); ?>
[...]
This is just to give you an example of the logic involved, but I wouldn't use the code as I've provided it as it is incredibly insecure, and doesn't check the existence of files, etc.
I know you're just getting started, and it's a lot to take in at once, but you might want to consider using a PHP framework such as Zend or Symfony, or CakePHP to take advantage of some routing and templating solutions that have already been set up for you.

How do you include multiple page content in one php include file?

I am wondering how would I include various elements (header, footer, nav), in one php file to be included on various pages, rather than creating multiple php files to be called separately?
In my includes file I have the following code:
<?php
echo '<h1 class="sub-elements">The elements for the current submission period are:<span style="font-weight:bold; color:#ff6000;"> Carnival, Residue, Maudlin</span>.</h1>';
?>
Outputting onto an html page that is running php I have:
<?php include('php-includes/current-elements.php');?>
Is there a way to include a particular div or class, something other than the entire file itself?
I just didnt want to create a separate php include file for every little element that i want to include on the same page.
The code below is what I had within the same include file to call a different element to be displayed on another page.
<?php
function elements ()
{
echo'<h1 class="sub-elements">The elements for the current submission period are:<span style="font-weight:bold; color:#ff6000;"> TESTING</span>.</h1>';
elements();
}
?>
Any help would be great!
It sounds like you are trying to avoid templates. The basic idea is to define a separate file for each of head, footer, nav and include those from your content template.
head.php
<!doctype html> <html> ...
nav.php
<body> <a href=..> page1 </a> <a href=..> page2 </a> <a href=..> page3 </a>
foot.php
</body> </html>
And to create a complete page, you would do:
<?php
include 'head.php';
include 'nav.php'
An article about prune juice.
include 'foot.php';
?>
Now, if I understand correctly, you want to include only one file and be able to generate the various elements (head, nav, whathaveyou). You could do this by wrapping the include statements in functions:
ubertemplate
<?php
function head() { include 'head.php'; }
function nav() { include 'nav.php'; }
function randomElement() { ?>
An article about prune juice. <?php
}
function totalymisguideddynamiccontents() {
echo "<div> foobar <span> moo </span></div>"
}
function() { include 'foot.php'; }
?>
..then in your final page, call these functions:
uberpage
<?php
include 'ubertemplate.php';
?>
<?php head() ?>
<script src=superlib.js></src>
<?php nav() ?>
Yomama so big when she wears a yellow coat people yell TAXI!.
<?php foot() ?>
Finally, if I understand correctly and you think the uberpage approach seems like a good idea, ...then you should probably try it out. That may well be the only way to realize that it is flawed. I don't mean to mock your idea, but there are better ways to approach templates and the first way, the one you are trying to avoid, is cleaner (but that's only my opinion).
For a better way, look at twig templates or do some more research and find a framework that suits your needs.

Include external code on a web page ( php include() or get_header() )

I've started creating a custom html page for the first time and i've hit a bump. The code in the header will be the same in all my pages , so i want to put it in an external file (header.php) and just put 1 line of code in all my pages to link to it but it doesn't seem to be working .
Note - I want to include just basic html code ( not a function ) - i'm thinking that's why its not working but not sure.
HTML file :
<body>
<?php include('header.php') ?> // didn't work
<?php get_header(); ?> // didn't work
<div class="content"> </div>
</body>
PHP File :
<h1>TITLE</h1>
When i put the code directly on the page - it shows "TITLE"
When i try include or get_header , i get a blank page . I checked the codex and online posts but i've not been able to fix it .
Any help would be appreciated - Thanks
Try in your header.php:
<?php
echo "<h1>TITLE</h1>";
?>
Then where you want to insert the header:
<?php include '/header.php' ?>
The / character makes the path to header.php relative to your root.
<?php include("dyn_layout/cbside_php.php"); ?>
This works for me... just don't forget to rename your files to .php extension... including the file where the insertion is made.

Develop Results View Page in PHP/MySQL

This is probably going to be quite an easy question for everyone, and I have tried following and understanding tutorials, but I just cant get my head around it!!
Ok so for University me and my peers are creating a student assesment system, my task is to create a results view page.
Basically I have been given a file called index.php which has a template background with a header and footer thats just looks like a normal web page. I need to be able to display results from a table from a database (I dont have yet but can create a test to test it) that has data into a certain position of that index.php page.
I have phpadmin installed and have tried creating a test database and table to insert in, but it just doesnt work when i follow tutorials like this one http://www.siteground.com/tutorials/php-mysql/display_table_data.htm , i just cant understand it, which im sure if my fault!!!
Someone else is writing the query's ill need, but firstly im just trying to understand how I even do this, and how i tell it to go to the index.php page, and where to place the table on that page.
This is the php code for the index.php file if i open it in notepad ++
<?php
/*use template to create pages*/
include('templates/header.html');
include('templates/topMenu.html');
?>
<div id="contentwrap">
<div id="content">
<div style="clear: both;"> </div>
</div>
<?php
require_once('templates/sidebarStudent.php');
?>
<div style="clear: both;"> </div>
</div>
<?php
include('templates/footer.html');
?>
So my question is do I just enter some code somewhere in this index.php file that tells it where to get the database and table from? and how do I tell it where to position the table in the page, or do I have to create seperate php files for this?
Please help! :(
If you were able to create some sort of test database, then you can use this basic code example to get up and running. You can put this inside one of those <div> tags to get the content to show up where you need it. Make sure you update the parameters below for your database username, password, database name, etc.
<?php
$link = mysql_connect('localhost', 'db_user_name_here', 'db_password_here');
mysql_select_db('db_name_here', $link);
$result = mysql_query('SELECT * FROM table_name_here');
while ($row = mysql_fetch_assoc($result)) {
echo $row['column_name_here'] . "<br>";
}
mysql_close($link);
?>
If you still have trouble, then you'll need to make sure you have a proper database user, a database, and a table inside that database. It might be best to look for a tutorial because it will likely walk you through the steps necessary better than I can do here.
Excellent question.
It rarely occurs when someone even bother with it.
Most of time the usual scenario for the PHP script is just to put everything into one perfect mess.
Yes, you have to always use separate files for the PHP and HTML code (business and presentation logic to be correct).
The guy who is writing queries have to put all the code into separate file which collects all the data into some variables which have to be passed into template file.
Then his code has to set the name of the file which contains the page template.
And finally call your main page template.
So, the index.php file should contain NO HTML code, but PHP only:
<?
//include settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA = db::getarr("SELECT * FROM links");
// setting title for using in the main template
$pagetitle = "Links to friend sites";
//etc
//set page template filename
$tpl = "links.tpl.php";
//and then finally call a template:
include "main.tpl.php";
?>
where main.tpl.php is your main site template, including common parts, like header, footer, menu etc (there is no need to have header and footer in the separate files):
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
and links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
Eventually you may come to more complex designs, like with front controller one, but for the first site this one is both easy and powerful.

Having includes with variables in two places at once

I have a small situaton here. I'm building a custom CMS for one of my websites.
Below is the code for the main index page:
<?php
require("includes/config.php");
include("includes/header.php");
if(empty($_GET['page'])) {
include('pages/home.php');
} else {
if(!empty($_GET['page'])){
$app = mysqli_real_escape_string($db,$_GET['page']);
$content = mysqli_fetch_assoc(mysqli_query($db, "SELECT * FROM pages_content WHERE htmltitle = '$app'")) or die(mysqli_error($db));
$title = $content['title'];
$metakeywords = $content['htmlkeywords'];
$metadesc = $content['htmldesc'];
?>
<h1><?php echo $content['title']; ?></h1><hr /><br />
<div id="content"><?php echo $content['content']; ?></div>
<? } else { include('includes/error/404.php');} }
include('includes/footer.php'); ?>
The file, includes/header.php contains code to echo variables, such as, page title and meta stuff.
The issue is that when the include("includes/header.php"); is where it is, outside of the if conditions, it will not echo the varables, obviously, however, I can't put the include in the if condition otherwise, the home page, which does not require any url variables will show without these conditions.
What do I do?
You can't really write code like this for too long. It's ok to for start, but you will soon realize it's hard to maintain. The usual way is to split it into a few steps.
First check input and determine on which page are you
If you know you are on the homepage, include something like includes/templates/homepage.php
Otherwise try to load the page from the database
If it worked, include includes/templates/page.php
Otherwise include includes/templates/404.php
Each of the files in includes/templates will output the whole page, i.e. they all include the header, do something and include the footer. You can use for example Smarty templates instead of PHP files, which will make the approach obvious.
Once you have this, you can split the code even more. Instead of loading the page directly from index.php, include another file which defines a function like load_page($name) and returns the page details.
Then a few more changes and you realize you are using the MVC approach. :) The functions that load data from the database are your Models, the Smary templates are Views and the PHP files that put them together are Controllers.

Categories