Kamil
Kamil

Reputation: 13931

How to manage pages/forms on PHP application?

im new in PHP and im trying to write simple online shop.

Lets say have index file like this:

<?php  
require_once '/inc/db.php';
$db = new Db();
?>  

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
        <div id="header"><?php require_once("header.php"); ?></div>

        <div id="content">
                <?php
                    // i have no idea what to put here
                ?>
        </div>

        <div id="footer"><?php require_once("footer.php"); ?></div>
</body>
</html>

I created files "add_category.php" and "add_product.php", they contain html forms. They are working, but i want to display that form in content div, and save data in database and i have problem. I want to apply my global header, footer etc. and i don't want to copy my layout from index file to each form of my application.

I have no idea:

I have some books about PHP, but there is no book that says how to build applications. They all are about PHP language and simple tasks on single pages/files.

I need simple pattern/example/article about managing forms/pages and communicate between them (by POST for example). Tried to learn from Wordpress sources, but this is a little too complicated to analyze for me (big complicated registry, object caching etc.).

I HAVE NO PROBLEMS WITH PROGRAMMING IN GENERAL (im windows app programmer).

Upvotes: 0

Views: 1096

Answers (3)

Basti
Basti

Reputation: 4042

Just pass a GET-parameter ?page=add_product or ?page=add_category to your index.php and include a matching php-script:

<?php  
require_once '/inc/db.php';
$db = new Db();

// if no page-parameter was send, have a default page to display.
define("DEFAULT_PAGE", "my_default_page.php");

if (isset($_GET["page"]))
{
    switch ($_GET["page"])
    {
        case "add_product": $page = "add_product.php"; break;
        case "add_category": $page = "add_category.php"; break;
        // add more cases here
        default : $page = DEFAULT_PAGE;
    }
}
else
    $page = DEFAULT_PAGE;
?>  

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
        <div id="header"><?php require_once("header.php"); ?></div>

        <div id="content">
                <?php
                    require $page;
                ?>
        </div>

        <div id="footer"><?php require_once("footer.php"); ?></div>
</body>
</html>

Edit: MVC-Approach:

/index.php
/controllers/home.php               Default page with some welcome stuff.
/controllers/new_product.php        Display form for creating a product.
/controllers/create_product.php     Process POST-data and create a product.
/controllers/new_category.php       Display form for creating a category.

index.php:

define("DEFAULT_PAGE", dirname(__FILE__)."/controllers/home.php");

// Did the user pass page?
if (isset($_GET["page"])
// Does page contain a valid controller name?
&&  preg_match("~^[a-zA-Z_]+$~D", $_GET["page"])
// Does this controller exist?
&&  file_exists(dirname(__FILE__)."/controllers/".$_GET["page"].".php"))
{
    // Controller exists.
    $page = dirname(__FILE__)."/controllers/".$_GET["page"].".php";
}
else
    $page = DEFAULT_PAGE;

Upvotes: 1

Your Common Sense
Your Common Sense

Reputation: 157887

Instead of including your scripts into main site template you have to do quite contrary - include your templates into PHP scripts.
You may address your scripts separately or make a single entry point. Both methods doesn't differ too much, but I'd suggest to use former one for starter.

So, make your site consists of pages, page templates and main template.
Once your script called, it have to process data, and then load site template, which, in turn, will load page template.

An example layout is going to be like this: a page:

<?
//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";
?>

it outputs nothing but only gather required data and calls a template:

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>

and calls the actual page template:

<h2><?=$pagetitle?></h2>
<ul>
<? foreach($DATA as $row): ?>
<li><a href="<?=$row['link']?>" target="_blank"><?=$row['name']?></a></li>
<? endforeach ?>
<ul>

For the form it is good idea to make form's action the very same page (so, you can leave form action simply blank).
The request would be sent to the same page, at the top of which you may put a code like this:

<?  
if ($_SERVER['REQUEST_METHOD']=='POST') {  

  $err = array();
  //performing all validations and raising corresponding errors
  if (empty($_POST['name']) $err[] = "Username field is required";  
  if (empty($_POST['text']) $err[] = "Comments field is required";  

  if (!$err) {  
    //if no errors - saving data and redirect
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
  }  else {
    // all field values should be escaped according to HTML standard
    foreach ($_POST as $key => $val) {
      $form[$key] = htmlspecialchars($val);
    }
} else {
  $form['name'] = $form['comments'] = '';  
}
$tpl = "form.tpl.php";
include "template.php";
?>  

it will process your data and either redirect to the same page on success or show the filled form on error

the main idea of this is user-friendly form handling and business logic/display logic separation while keeping most natural site layout - separate files for the different site modules yet common design.

Upvotes: 3

Tchoupi
Tchoupi

Reputation: 14691

Start with basics: http://www.tizag.com/phpT/forms.php

First you probably want to post your data to your form, so add action="add_category.php" and method="post" to your form. It's always better to POST to avoid bugs while passing data in the URL (GET).

Then in the PHP part, first check the $_SERVER['REQUEST_METHOD'] variable. If it says 'POST' it means that the form was submitted. Check all your vars using isset() to avoid php notices, and do any validation you need to do on those variable. Exemple: $_POST['category'] > 0.

I usually store all my errors in one $errors array and display errors based on the previous validation.

count($errors) == 0 means you have no error, you can then insert / update your database, and you can either show a message to the user stating that the insertion was done, or redirect him using a Location: header to the category list for instance.

Upvotes: 0

Related Questions