Develop Results View Page in PHP/MySQL - php

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.

Related

PHP program flow with multiple queries and arrays? [duplicate]

I'm looking for advice on the best practice for separating site content up into logical blocks. I want a header and footer that are constant throughout the site, so that if I have several pages of different content, they will all look as below — changes made to the header and footer then update automatically without me having to change each individual page.
<?php
include 'header.php';
?>
<body>
<p>page content here</p>
</body>
<?
include 'footer.php';
?>
The header.php would contain the opening <html>, <head> and static content, and the footer.php would contain any extra static content and the closing </html> tag. So, my question is: Is this a good approach? I'm worried that spreading the <html> tags across multiple files is bad practice. If so, what is the right way to approach this kind of design?
Nope, your approach is wrong.
Here are main faults in your design:
You're assuming that header.php would be called on the every page call. That's wrong.
You're assuming that header.php will always be static. That's wrong.
You forgot to create a template for the page itself.
The main rule everyone have to learn by heart:
Not a single character has to be sent into browser, until all data gets ready.
Why?
it's 2011 today. AJAX era. What if your code will have to send JSONed data instead of whole HTML page?
there is a thing called HTTP header. Sometimes we have to send them. And it's gets impossible if you already have your ornate HTML header sent.
it's for just 4-page site. Okay. Imagine you've got lucky and got a request for another 4-page site. You will have to change only templates and don't touch engine files. That's really great benefit.
Imagine you're going to make a custom <title> tag for your pages, based on the page content. Isn't it extremely common thing? But you can't make it without using templates.
So, you have to have one common site template containing header and footer and also dedicated templates for the every php script.
An example layout is going to be like this:
.1. page itself.
it outputs nothing but only gather required data and calls a template:
<?php
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
$pagetitle = "Links to friend sites";
//etc
//and then call a template:
$tpl = "links.tpl.php";
include "template.php";
?>
.2. template.php which is your main site template,
consists of your header and footer:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<?php include $tpl ?>
</div>
</body>
</html>
.3. and finally links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<?php foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<?php endforeach ?>
<ul>
easy, clean and maintainable.
In building off of Your Common Sense's answer, there's not a good reason to have 2 files for every page. You can easily combine your template (YCS called this .tpl.php) and your actual page into one file.
First, start off with a class that you can expand as your template needs expand:
<?php
#lib/PageTemplate.php
class PageTemplate {
public $PageTitle;
public $ContentHead;
public $ContentBody;
}
Then, make your layout:
<?php
# layout.php
require_once('lib/PageTemplate.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<title><?php if(isset($TPL->PageTitle)) { echo $TPL->PageTitle; } ?></title>
<?php if(isset($TPL->ContentHead)) { include $TPL->ContentHead; } ?>
</head>
<body>
<div id="content">
<?php if(isset($TPL->ContentBody)) { include $TPL->ContentBody; } ?>
</div>
</body>
</html>
And finally, add your page with the body content:
<?php
#Hello.php
require_once('lib/PageTemplate.php');
# trick to execute 1st time, but not 2nd so you don't have an inf loop
if (!isset($TPL)) {
$TPL = new PageTemplate();
$TPL->PageTitle = "My Title";
$TPL->ContentBody = __FILE__;
include "layout.php";
exit;
}
?>
<p><?php echo "Hello!"; ?></p>
This is a basic approach but, yeah, it does work :) I sure would bother with a lot of templating and OOP but you are definitely on the right path
As i can't comment anymore, then i will answer here ;) If he need a custom title then he needs some more advanced functions. So, as i told, this is a basic approach. But in the end, if he really have a static header/footer, and really use them everywhere, well, yes, this is a good way to go.
So ofc you could bother with some advanced headers with parameters you could feed on each page. You could go on a whole MVC stuff. In the end just tell him to use a pre-made framework and stop bothering. How could he learn if you don't let him do some trial and error ?
index.php -- includes header, footer, and content based on REQUEST variable.
header.php -- header content
footer.php -- footer content
content1.php, content2.php, etc.
index.php:
<?php
include ('header.php');
// VERY IMPORTANT - do not use the GET variable directly like this
// make sure to filter it through a white-list
include(basename($_GET['page']).'.php');
include ('footer.php');
?>
if you want the URL to go www.domain.com/pagename where the page you're trying to load into index.php is "pagename", use HTACCESS and do some URL Rewriting: http://corz.org/serv/tricks/htaccess2.php

Where to start when building a website from scratch using index.php

I have decided to build my site website from scratch, rather than using Wordpress, Magento or a bootstrap template.
I'm looking for a good guide to do so, Code Academy and w3schools are good for learning specific elements of HTML and CSS but I'm looking for a good guide for how to structure my site.
I am playing around with creating an index.php using e.g. to include all element of the page to make creating the individual pages of my site clean and more efficient that including the include for header and footer on each page.
One issue I am having is that I am struggling to understand how to include the different pages within the index.php. I have searched for this but I obviously am not finding the correct words to search for this as I'm struggling to find a decent answer. I think I need something along the lines of a wildcard so that I can say to call all html files within my pages folder so that all pages are using my index.php template.
Below is my index.php to help explain. Thanks in advance and apologies if this question is answered elsewhere on the site, I searched but did not find anyone else answering the same question!
<!DOCTYPE html>
<html>
<php include "head.html" ?>
<body>
<div class="container">
<php include "navigation.html" ?>
<div class="wrapper">
<php include pages/*.html ?>
</div>
</div>
</body>
<php include "footer.html" ?>
</html>
It looks to me like you are almost there. I am not sure of the syntax you are using works, but the code below is used in some of my sites to include a header:
<?php include('includes/header.php'); ?>
This means include the code in the file 'header.php' that is in the folder 'includes', which is on the same level as the file that is calling the code.
The result would be that the 2 files are merged in to one when the page is loaded, with the code from header.php being inserted in place of the line
<?php include('includes/header.php'); ?>
You need to pass variables in URL e.g index.php?page=home and then in your index.php file you shoud get that variable $page = $_GET['page']. Now in $page you have name of the file to include
<?php include($page.'.html') ?>
For now, I skipped security issues of that solution.

Filtering data from DB using several links delivered by PHP

UPDATE
I've solved by myself this problem. It wasn't a problem at all, just because lack of experience.
Everything went from a misunderstanding of the $_GET variable and for what can be used, and PHP data types as well. When I did read twice the PHP documentation, I understood that it is actually an array and I could put several variables and pass several parameters through it, as it is persistent.
From there, the rest was piece of cake. With a single include and a bunch of functions I can do all the database petitions and output them as I want!
I'm glad I've been able to solve it by myself, and thanks to Passerby, who made me think about how I was managing the $_GET variable.
I had to redo this question because last one was a dull brick of text. Let's simplify.
Let's say I have a fruit DB with 'n' items. The cols are the following:
Name of the fruit.
Country of origin.
Color.
On the index.php I have sidebar.php with links and a content.php with some text into it. Like this:
<!--html code here-->
<?php include('includes/content.php') ?>
<?php include('includes/sidebar.php') ?>
<!--more html code here-->
The links of the sidebar.php are like these:
Browse by country
Browse by color
etcetera.
searchDB.php is generated with the same layout than index.php with this difference:
<!--html code here-->
<div id="content">
<?php include('functions/fruit_list.php') ?>
</div>
<?php include('includes/sidebar.php') ?>
<!--more html code here-->
inside fruit_list.php there's a script that shows all countries into the content <div>
once you click on 'browse by country'. It generates some hyperlinks as well which I'm unable to manage or figure how to link them to a function, or somewhere that allows me to go one level deeper (for instance if you click into 'Japan', I'd like to list all fruits from Japan).
If possible, the new generated list (all fruits from Japan), should be on the same content div.
Any ideas? Thoughts? I have a wrong approach to do this?

Adding PHP to a static site. Not sure if my workflow is right

Let's try to explain the title of my question to be the more concise I can: I'm basically designing a static HTML website from scratch. Nothing to worry about here.
The point is that I'm trying to include some links that will retrieve some items (a product inventory) from a database (and therefore the site won't be so 'static' anymore), as there're > 300 products and creating an html for each one is not feasible.
After googling and reading several sites for days, the "easiest" solution I came up with is to use PHP and MySQL. Again, nothing to worry about. Just took my time for reading documentation and move along.
My question is more related about the correct workflow for integrating both worlds. Let's see my idea in code:
This is one schematic example of the page where you can browse some products (e.g: product.html):
<html>
<head>
<title>My Site - These are our products</title>
</head>
<body>
<!--Site goes here-->
Search by name
Search by color
<!--rest of site goes here-->
</body>
</html>
Where the links
product_search_by_name.php
product_search_by_color.php
are actually a modified clone of the same page (product.html). This is, keeping same html code, plus the .php code embedded into it, as I want to have the DB results displayed into a div on that same page, keeping exactly same layout.
So, am I doing this right if I want to maintain the appearance of the whole website? I'm absolutely wrong from the base and should start again? Should I give up and work selling frappuchinos on a Star*ucks?
As a sample of the idea I want to achieve is the following: http://www.w3schools.com/tags/default.asp (when you click on the left menu bar, the center zone updates with the content). By the way, are they using AJAX on that website to update just the center zone, or I'm misunderstanding what is AJAX for?
I'm sure I'm missing something but I'm too confused to separate the sheep from the goats, so I'd thank a lot any tips you can give to me (and additional documentation on the internets to read as well).
There are two main ways to merge or migrate from static HTML to dynamic HTML (PHP, PERL, whatever).
(1) One is to have most of the contest as HTML, and the stuff like inventory as dynamic.
<html>
<head>
<title>My Site - These are our products</title>
</head>
<body>
<h1>My Site - These are our products</h1>
<?php
// php code to retrieve links
?>
</body>
</html>
(2) To have a full PHP site.
<?php
echo "<html>" . "\n";
echo "<head>";
echo "My Site - These are our products"
echo "</head>";
echo "<body>" . "\n";
// php code to retrieve links
echo "</body>" . "\n";
echo "</html>" . "\n";
?>
Many developers start by merging both HTML & PHP.
I suggest to learn how to do a very simple but full php site, connect to a database, retrieve some records with a S.Q.L. query, display them as read-only text or links, and later you may change to the other HTML plus PHP way of doing things.
There are several editors and tools to help develop in PHP, specially by looking for a PHP function, or just highlight HTML tags. Scintilla (Linux) or Notepad++ in windowze, its a very simple yet useful tool.
Cheers.
Well, if you want it to make it using Ajax ...
You might want to do the following.
Create the two files as you said, those are not to be included in the HTML file.
Create a JavaScript function to call the files, You can use jQuery api, to link to php. http://api.jquery.com/jQuery.post/ or http://api.jquery.com/jQuery.get/
Link the click of the button inquired to call the JavaScript function, and add html you get from php to the tag you want.
You can create a index.php page and put down your html code in it. It looks like this
<html>
<body>
<!--- links goes here -->
Search Products
</body>
</html>
If you are retrieving products from a database and if you want to create multiple links for the products create a function in your function.php which pulls all the product name from the database. Now add this function into your index.php
index.php
<?php include ('functions.php')?>
<html>
<body>
<h3>Product List</h3>
product name
</body>
</html>
Always embed html in php file. Do not embed php in html file. File should have .php extension.

Do search engines have trouble with urls like somesite.com/index.php?page=photos

I'm new to php coding, web development, and search optimization - so newbie overall. In the process of learning php and web development I've been trying out different website architectures and layouts. One I'm working on uses an approach like the following:
I have one index.php page which always loads a header.php, sidebar.php, and footer.php. The index.php also contains a switch so that depending on the page variable the index.php is passed it loads different core content. So for example a examplesite.com/index.php?page=photos and examplesite.com/index.php?page=stories would both have the same header, footer, and side bar but one would have photos and one would have stories as the main content.
<?php $page = $_GET['page'];?>
<?php include("header.php"); ?>
<?php include("nav.php"); ?>
<?php
switch ($page)
{
case 'play':
include("photos.php");
break;
case 'cards':
include("stories.php");
break;
default:
include("frontpage.php");
}
?>
<?php include("footer.php"); ?>
My navigation is made up of href="index.php?page=..." links so choosing a menu button on the index page essentially calls itself passing it the new core to load.
I have no idea if this is a totally unorthodox approach but it all started because I was initially going to create a wordpress theme but then halfway through decided not to do it in wordpress.
What i'm concerned about are what drawbacks could be associated with this approach when it comes to search engines, indexing, seo etc.
What are other drawbacks or issues I should be thinking about that maybe I'm not?
Thanks in Advance!
I have no idea if this is a totally unorthodox approach
There is nothing essentially "unorthodox" in using a query string to load various pages. Billions of sites using this approach. Search engines can index such pages all right.
Nevertheless,
I have one index.php page which always loads a header.php, sidebar.php, and footer.php.
This is wrong concept.
Having an index.php file only to load header and footer makes no sense and makes your site plainly unusable.
Here are main faults in your design:
You're assuming that header.php would be called with the every page call. That's wrong.
You're assuming that header.php will always be static. That's wrong.
You forgot to create a template for the page itself.
The main rule everyone have to learn by heart:
Not a single character has to be sent into browser, until all data gets ready.
Why?
it's 2012 today. AJAX era. What if your code will have to send JSONed data instead of whole HTML page?
there is a thing called HTTP header. Sometimes we have to send them. And it's gets impossible if you already have your ornate HTML header sent.
Separating display logic from the business logic will let you use the same php code on many sites. You will have to change only templates and don't touch engine files. That's really great benefit.
Imagine you're going to make a custom <title> tag for your pages, based on the page content. Isn't it extremely common thing? But you can't make it without using templates.
So, you have to have one common site template containing header and footer and also dedicated templates for the every php script.
And these templates have to be called only when all business logic is done - i.e. you have got all your data ready.
An example layout is going to be like this:
.1. page itself.
it outputs nothing but only gathers required data and then calls a template:
<?
//include our settings, connect to database etc.
include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php';
//getting required data
$DATA=dbgetarr("SELECT * FROM links");
$pagetitle = "Links to friend sites";
//etc
//and then call a template:
$tpl = "links.tpl.php";
include "template.php";
?>
.2. template.php which is your main site template,
consists of your header and footer:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My site. <?=$pagetitle?></title>
</head>
<body>
<div id="page">
<? include $tpl ?>
</div>
</body>
</html>
.3. and finally links.tpl.php is the actual page template:
<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><?=$row['name']?></li>
<? endforeach ?>
<ul>
this way you'd need no index with includes at all

Categories