Pages

User Registration with Codeigniter

Sunday, May 20, 2012
In this tutorial, I will explain you user registration with CI. If you are a very newbies in CI, you can start by reading How to start with CI? or read this excellent article Everything You Need to Get Started With CodeIgniter.

If you have finished our previous tutorial, we can start this tutorial now. The CI classes we have to learn in this tutorial are session and form validation. I believe that you would be familiar with PHP session.

Requirement

Download the latest CI version from the following link.

CodeIgniter

Step 1:Configuration

Open application/config/database.php, and change the following database configuration to fit your mysql configuration.

$config['hostname'] = "localhost";

$config['username'] = "myusername";

$config['password'] = "mypassword";

$config['database'] = "mydatabase";

$config['dbdriver'] = "mysql";

 

Then open application/config/config.php

$config['base_url'] = 'http://localhost/ci_user';

$config['encryption_key'] = '1234';

 

Open application/config/autoload.php

$autoload['libraries'] = array('session','database');

and

$autoload['helper'] = array('url','form');

 

Open application/config/routes.php, change default controller to user controller as we’ll create later on this tutorial.

$route['default_controller'] = 'user';

Step 2:Creating User table

We need to create a table in our database. Import following SQL statement via phpMyAdmin or any other MySQL tool.
CREATE TABLE `user` (
`id` INT( 50 ) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR( 50 ) NOT NULL ,
`email` VARCHAR( 100 ) NOT NULL ,
`password` VARCHAR( 255 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB

Step 3:Creating our Controller

Create a blank document in the controller file (application -> controller) and name it user.php, in the document add all the following code.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User extends CI_Controller{
 public function __construct()
 {
  parent::__construct();
  $this->load->model('user_model');
 }
 public function index()
 {
  if(($this->session->userdata('user_name')!=""))
  {
   $this->welcome();
  }
  else{
   $data['title']= 'Home';
   $this->load->view('header_view',$data);
   $this->load->view("registration_view.php", $data);
   $this->load->view('footer_view',$data);
  }
 }
 public function welcome()
 {
  $data['title']= 'Welcome';
  $this->load->view('header_view',$data);
  $this->load->view('welcome_view.php', $data);
  $this->load->view('footer_view',$data);
 }
 public function login()
 {
  $email=$this->input->post('email');
  $password=md5($this->input->post('pass'));

  $result=$this->user_model->login($email,$password);
  if($result) $this->welcome();
  else        $this->index();
 }
 public function thank()
 {
  $data['title']= 'Thank';
  $this->load->view('header_view',$data);
  $this->load->view('thank_view.php', $data);
  $this->load->view('footer_view',$data);
 }
 public function registration()
 {
  $this->load->library('form_validation');
  // field name, error message, validation rules
  $this->form_validation->set_rules('user_name', 'User Name', 'trim|required|min_length[4]|xss_clean');
  $this->form_validation->set_rules('email_address', 'Your Email', 'trim|required|valid_email');
  $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
  $this->form_validation->set_rules('con_password', 'Password Confirmation', 'trim|required|matches[password]');

  if($this->form_validation->run() == FALSE)
  {
   $this->index();
  }
  else
  {
   $this->user_model->add_user();
   $this->thank();
  }
 }
 public function logout()
 {
  $newdata = array(
  'user_id'   =>'',
  'user_name'  =>'',
  'user_email'     => '',
  'logged_in' => FALSE,
  );
  $this->session->unset_userdata($newdata );
  $this->session->sess_destroy();
  $this->index();
 }
}
?>
In the index() function,

if(($this->session->userdata('user_name')!=""))

the above code is equal to the following code in php.

if($_SESSION['user_name']!="")

It means that if the user_name is not equal to the null, this user have already logged in. So we will go to welcome() function. Else we will show registration from view.

You will understand next login() and thank() functions I think.

In the registration() function, firstly we load the form_validation library. And then we set the rules for our form field. The trim rule is equal to the php trim() function and you will understand the others I think. And then we run the form validation. If the result is false, we will go to index() function. Else we will add user data and will go to thank() function.

In the logout() function, we will unset and destroy the session data and will go to the index() function.

Step 4:Creating Model

Create a blank document in the model file (application -> model) and name it user_model.php, in the document add all the following code.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
 public function __construct()
 {
  parent::__construct();
 }
 function login($email,$password)
 {
  $this->db->where("email",$email);
  $this->db->where("password",$password);

  $query=$this->db->get("user");
  if($query->num_rows()>0)
  {
   foreach($query->result() as $rows)
   {
    //add all data to session
    $newdata = array(
      'user_id'  => $rows->id,
      'user_name'  => $rows->username,
      'user_email'    => $rows->email,
      'logged_in'  => TRUE,
    );
   }
   $this->session->set_userdata($newdata);
   return true;
  }
  return false;
 }
 public function add_user()
 {
  $data=array(
    'username'=>$this->input->post('user_name'),
    'email'=>$this->input->post('email_address'),
    'password'=>md5($this->input->post('password'))
  );
  $this->db->insert('user',$data);
 }
}
?>
In the login() function,

$this->db->where("email",$email);

$this->db->where("password",$password);

the above two line will produce the following query in MySQL:

WHERE email='$email' AND password='$password'

$this->session->set_userdata($newdata);

This above code will set our user data to the session variable.

Step 5:Designing our view files

Create a blank document in the views file (application -> views) and name it header_view.php, in the document add all the following code.
<!DOCTYPE html>
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title><?php echo (isset($title)) ? $title : "My CI Site" ?> </title>
 <link rel="stylesheet" type="text/css" href="<?php echo base_url();?>/css/style.css" />
</head>
<body>
 <div id="wrapper">
Create a blank document in the views file (application -> views) and name it footer_view.php, in the document add all the following code.
<div id="footer">
  &copy; 2011 <a href="http://tutsforweb.blogspot.com/">TutforWeb</a> All Rights Reserved.
 </div><!-- <div class="footer">-->
 </div><!--<div id="wrapper">-->
</body>
</html>
Now let's create our registration view file.

I will use the tableless form design. It has some benefits:

1.Faster loading of pages

2.Efficiency

3.Consistency

4.SEO advantage

5.Layouts and design sophistication

6.Bandwidth efficiency

Create a blank document in the views file (application -> views) and name it registration_view.php, in the document add all the following code.
<div id="content">
<div class="signup_wrap">
<div class="signin_form">
 <?php echo form_open("user/login"); ?>
  <label for="email">Email:</label>
  <input type="text" id="email" name="email" value="" />
  <label for="password">Password:</label>
  <input type="password" id="pass" name="pass" value="" />
  <input type="submit" class="" value="Sign in" />
 <?php echo form_close(); ?>
</div><!--<div class="signin_form">-->
</div><!--<div class="signup_wrap">-->
<div class="reg_form">
<div class="form_title">Sign Up</div>
<div class="form_sub_title">It's free and anyone can join</div>
 <?php echo validation_errors('<p class="error">'); ?>
 <?php echo form_open("user/registration"); ?>
  <p>
  <label for="user_name">User Name:</label>
  <input type="text" id="user_name" name="user_name" value="<?php echo set_value('user_name'); ?>" />
  </p>
  <p>
  <label for="email_address">Your Email:</label>
  <input type="text" id="email_address" name="email_address" value="<?php echo set_value('email_address'); ?>" />
  </p>
  <p>
  <label for="password">Password:</label>
  <input type="password" id="password" name="password" value="<?php echo set_value('password'); ?>" />
  </p>
  <p>
  <label for="con_password">Confirm Password:</label>
  <input type="password" id="con_password" name="con_password" value="<?php echo set_value('con_password'); ?>" />
  </p>
  <p>
  <input type="submit" class="greenButton" value="Submit" />
  </p>
 <?php echo form_close(); ?>
</div><!--<div class="reg_form">-->
</div><!--<div id="content">-->
In this view we echo our validation errors like below.

<?php echo validation_errors('<p>'); ?>

In our input fields, we use the below function.

<?php echo set_value('user_name'); ?>

Because of above function the original data will be show in the form, if there is an error after the validation rules. So we have only been dealing with errors.

Below code is thank_view.php and welcome_view.php.
<div id="content">
<div class="signup_wrap">
<div class="signin_form">
 <?php echo form_open("user/login"); ?>
  <label for="email">Email:</label>
  <input type="text" id="email" name="email" value="" />
  <label for="pass">Password:</label>
  <input type="password" id="pass" name="pass" value="" />
  <input type="submit" class="" value="Sign in" />
 <?php echo form_close(); ?>
</div><!--<div class="signin_form">-->
</div><!--<div class="signup_wrap">-->
<h1>Thank!</h1>
</div><!--<div id="content">-->
<div class="content">
  <h2>Welcome Back, <?php echo $this->session->userdata('username'); ?>!</h2>
  <p>This section represents the area that only logged in members can access.</p>
  <h4><?php echo anchor('user/logout', 'Logout'); ?></h4>
</div><!--<div class="content">-->
We need some css code to design our registration form. Copy following code and paste your css>style.css.
@charset "utf-8";
/* CSS Document */
body{
background-color:#FFF;
font-family:Monaco,Consolas,'Lucida Grande','Lucida Console';
font-size:16px;
text-shadow:rgba(0,0,0,0.01) 0 0 0;
}
#wrapper{
width:960px;
margin:0 auto;
}
#content{
width:960px;
margin:5px;
float:left;
}
/************************************************/
.signup_wrap{
height:25px;
width:100%;
padding:5px;
background-color:#2A1FFF;
}
.signin_form{
float:right;
}
.signin_form input{
width:80px;
}
.reg_form{
width:460px;
padding:20px;
margin:0 auto;
border:3px solid #DFDFDF;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#cbd4e5));
background: -moz-linear-gradient(top,  #fff,  #cbd4e5);
filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff', endColorstr='#cbd4e5');
}
.form_title,
.form_sub_title{
font-size:20px;

font-family:"Lucida Grande",Tahoma,Verdana,Arial,sans-serif;
font-size:20px;
font-weight:bold;
}
.form_sub_title{
font-weight:normal;
padding:6px 0 15px 0;
}
.reg_form p{
width: 300px;
clear: left;
margin: 0;
padding: 5px 0 8px 0;
padding-left: 155px; /*width of left column containing the label elements*/
border-top: 1px dashed gray;
height: 1%;
}
.reg_form label{
font-weight: bold;
float: left;
margin-left: -155px; /*width of left column*/
width: 150px; /*width of labels. Should be smaller than left column (155px) to create some right margin*/
}
input{
padding:3px;
color:#333333;
border:1px solid #96A6C5;
margin-top:2px;
width:180px;
font-size:11px;
}
.greenButton{
width:auto;
margin:10px 0 0 2px;
padding:3px 4px 3px 4px;
color:white;
background-color:#589d39;
outline:none;
border:1px solid #006600;
font-weight:bold;
}
.greenButton:active{
background-color:#006600;
padding:4px 3px 2px 5px;
}
.error{
color:#F00;
}
#footer{
color:#fff;
padding-top:20px;
text-align:center;
background: #454546; 
height: 20px;
clear:both;
}
Now our form is finished. Don’t hesitate to ask me, if something goes wrong on your side.
In the next tutorial we will discuss jQuery Ajax with CI.
Download Source Code
Read more ...

Auto complete text box with PHP, jQuery and MySql

Thursday, May 17, 2012
In this tutorial I want to show you how easy to do a auto complete text box with PHP, jQuery and MySql.

Firstly download the autocomplete jQuery plugin and extract it to your hard drive.
And then create a folder in your localhost. Copy jquery.autocomplete.css and jquery.autocomplete.js file to your project folder. And you will also need jquery.js. Now we can start our project.

Creating database table


We need to create a table in our database before writing our script. I also add some data for this table. Import following SQL statement via phpMyAdmin or any other MySQL tool.

CREATE TABLE `tag` (
  `id` int(20) NOT NULL auto_increment,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;

INSERT INTO `tag` (`id`, `name`) VALUES
(1, 'php'),
(2, 'php frameword'),
(3, 'php tutorial'),
(4, 'jquery'),
(5, 'ajax'),
(6, 'mysql'),
(7, 'wordpress'),
(8, 'wordpress theme'),
(9, 'xml');

index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Auto Complete Input box</title>
<link rel="stylesheet" type="text/css" href="jquery.autocomplete.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.autocomplete.js"></script>
<script>
 $(document).ready(function(){
  $("#tag").autocomplete("autocomplete.php", {
        selectFirst: true
  });
 });
</script>
</head>
<body>
<label>Tag:</label>
<input name="tag" type="text" id="tag" size="20"/>
</body>
</html>

autocomplete.php

This file is called from our jquery script. This php script is easy to follow.
<?php
 $q=$_GET['q'];
 $my_data=mysql_real_escape_string($q);
 $mysqli=mysqli_connect('localhost','username','password','databasename') or die("Database Error");
 $sql="SELECT name FROM tag WHERE name LIKE '%$my_data%' ORDER BY name";
 $result = mysqli_query($mysqli,$sql) or die(mysqli_error());

 if($result)
 {
  while($row=mysqli_fetch_array($result))
  {
   echo $row['name']."\n";
  }
 }
?>
We have done. Run your project and type in your text box you will see following screenshot.

By the way, I use the old jquery plug in this project. If you want to learn new thing, you can learn here and here. I create this tutorial because it is still useful and easy, although it is too old. I will also write about new jquery ui later.
Download Source Code
Read more ...

Ajax Login form with jQuery and PHP

Tuesday, May 15, 2012
In this tutorial, I will explain you how to create a ajax popup log in form with jquery and php.
Demo
Firstly let's create a folder in your www (for wamp) folder and name as ajax_login.

Crate a blank document in your favourite editor and paste following code in your document. And then save as index.php in your ajax_login folder. I have divided index.php into 2 parts. Below is our body part.

<body>
 <?php session_start(); ?>
 <div id="profile">
  <?php if(isset($_SESSION['user_name'])){
  ?>
   <a href='logout.php' id='logout'>Logout</a>
  <?php }else {?>
   <a id="login_a" href="#">login</a>
  <?php } ?>
 </div>
 <div id="login_form">
 <div class="err" id="add_err"></div>
 <form action="login.php">
  <label>User Name:</label>
  <input type="text" id="user_name" name="user_name" />
  <label>Password:</label>
  <input type="password" id="password" name="password" />
  <label></label><br/>
  <input type="submit" id="login" value="Login" />
  <input type="button" id="cancel_hide" value="Cancel" />
 </form>
 </div>
 <div id="shadow" class="popup"></div>
</body>

In this part, we use the php session variable to check whether the user have already logged in or not. To use session, you need to add session_start() function firstly. If the user has already logged in, we will show the logout. Else we will show login.

And then I create our login_form. We don't want to show this form before the user click the login link. So we need to add the css display:none to our css file for our login_form div.

Following code is our css file. So crate a blank document in your favourite editor and paste the following code. And then save as styles.css in our project folder.

.popup
{
   position: fixed;
   width: 100%;
   opacity: 0.9;
   top:0px;
   min-height:200px;
   height:100%;
   z-index: 100;
   background: #FFFFFF;
   font-size: 20px;
   text-align: center;
   display:none;
}
#login_form
{
 position:absolute;
 width:200px;
 top:100px;
 left:45%;
 background-color:#DDD;
 padding:10px;
 border:1px solid #AAA;
 display:none;
 z-index:101;
 -moz-border-radius: 10px;
 -moz-box-shadow: 0 0 10px #aaa;
 -webkit-border-radius: 10px;
 -webkit-box-shadow: 0 0 10px #aaa;
}

In the index.php head part, first attach the jQuery Library file. And you also need to attach our styles.css. Then write AJAX code into <head> section as following procedure:

<script type="text/javascript">
$(document).ready(function(){
 $("#login_a").click(function(){
  $("#shadow").fadeIn("normal");
  $("#login_form").fadeIn("normal");
  $("#user_name").focus();
 });
 $("#cancel_hide").click(function(){
  $("#login_form").fadeOut("normal");
  $("#shadow").fadeOut();
 });
 $("#login").click(function(){

  username=$("#user_name").val();
  password=$("#password").val();
  $.ajax({
   type: "POST",
   url: "login.php",
   data: "name="+username+"&pwd="+password,
   success: function(html){
    if(html=='true')
    {
     $("#login_form").fadeOut("normal");
     $("#shadow").fadeOut();
     $("#profile").html("<a href='logout.php' id='logout'>Logout</a>");

    }
    else
    {
     $("#add_err").html("Wrong username or password");
    }
   },
   beforeSend:function()
   {
    $("#add_err").html("Loading...")
   }
  });
  return false;
 });
});
</script>

Now let's create a login.php script.

<?php
 session_start();
 $username = $_POST['name'];
 $password = md5($_POST['pwd']);
 $mysqli=mysqli_connect('localhost','username','password','database');
 $query = "SELECT * FROM user WHERE username='$username' AND password='$password'";
 $result = mysqli_query($mysqli,$query)or die(mysqli_error());
 $num_row = mysqli_num_rows($result);
 $row=mysqli_fetch_array($result);
 if( $num_row >=1 ) {
  echo 'true';
  $_SESSION['user_name']=$row['username'];
 }
 else{
 echo 'false';
 }
?>

They are fairly straightforward to understand if you know about php and mysql. But you need to change username, password, database and table name for mysql. If you have a problem, don't hesitate to ask me.
The last thing we need to create is logout.php.

<?php
 session_start();
 unset($_SESSION['user_name']);
 header('Location: index.php');
?>

I think this tutorial will help you.

Download Source Code
Read more ...

Basic PHP Crash Course (part 7)

Saturday, May 12, 2012
In this post, we discuss how to retrieve or select the data from MySQL database to view our pizza order.
To do so we should create admin folder. So that we can prevent the customer from viewing our admin data.

Create a folder named admin in our pizza_shop folder.

Open the new document in your favourite editor or Notepad and type below code.


<html>
<head>
 <title>Amin Pannel</title>
</head>
<body>
<?php
 $con = mysqli_connect('localhost','root','','pizza') or die(mysqli_error());
 $sql="SELECT * FROM `order`";
 $result = mysqli_query($con,$sql) or die(mysqli_error());
 echo "<table width='100%'>";
  echo "<tr bgcolor='#FC0'>".
    "<td width='40%'>Customer Name</td>".
    "<td width='40%'>Address</td>".
    "<td width='20%' align='right'>Quantity</td>".
    "</tr>";
 while($row=mysqli_fetch_array($result)){
  echo "<tr valign='top'>".
    "<td width='40%'>".$row['name']."</td>".
    "<td width='40%'>".$row['address']."</td>".
    "<td width='20%' align='right'>".$row['quantity']."</td>".
    "</tr>";
 }#end of while loop
 echo "</table>";
?>
</body>
</html>

Save above file as index.php in our admin folder. Now if run this address http://localhost/pizza_shop/admin/ from your browser you will see like below.

Explanation

Our sql query is
"SELECT * FROM `order`"
* means all. This query will retrieve all data from our order table of pizza database.


If you familiar with programming, you can follow the code showed above picture. In this code I use while loop to show the order data.

Looping

In every programming, looping is an essential thing. In PHP, there are four kinds of looping. They are while, dowhile, for and foreach. You can use for loop if you know the looping time exactly. You can use dowhile if you want to execute at least once. If you don't know the looping time exactly, you can use while loop. The foreach loop is specially designed for use with arrays.

While Loop

This loop is simplest loop in PHP. It look like if statement. As long as the condition is true, it will execute the block repeatedly.

For our code as long as our order rows exist in our order table of the pizza database, the while loop will show the order rows.
mysqli_fetch_array($result) function will fetch the order table row one by one as an array. If there is no more rows, it will return NULL. When NULL return, while loop will stop.
Read more ...

Basic PHP Crash Course (part 6)

Thursday, April 19, 2012
In the early posts, we do not save the order data. To deliver the user order, we have to save the order data permanently. To do so we will need suitable database server. I will use MySQL.

What is MySQL?

MySQL is a Relational Database Management System. It can store, search, sort and retrieve data efficiently. You can use it freely under the GPL license. You can check more about MySQL in its official website www.mysql.com

What do we need?

In this series, we will learn about MySQL by using phpMyAdmin. It will make you more easy to create a database by using phpMyAdmin than command line because it is a GUI(Graphical User Interfaces) system. To use phpMyAdmin you don't need to install anything if you have installed xampp or wamp as mentioned in this post.
Type this address "http://localhost/phpmyadmin/" in your browser address bar. You will see like below screenshot.




Creating our Database

Click Databases from the menu.


Type in the text box as pizza for the database name and click "Create" button.


You will see your database name in the left menu like below screenshot.


Click your database name. You will see like below screenshot.



Type order in the Name field and type 4 in the Number of columns field like below screenshot. And then click Go button to crate a database table.


Now you need to fill the field name, type etc. like below screenshot.



A database table should have a primary key. So for our order table id field should be the primary key. Select in the Index select box as PRIMARY and set the A_I(AUTO_INCREMENT) check box that will increase automatically our id field number.


Then click Save button.


Now you have created a database table to save your customer order.

PHP and MySQL

It is time to connect the MySQL database by using PHP.
Firstly I want to introduce you to the PHP built-in functions that can connect to the MySQL.

mysqli_connect("hostname","username","password","databasename")

Above function will help you to connect the MySQL database. So you need to know the parameter values.
hostname - Hostname running database server. Default is localhsot. For our xampp or wamp is also localhost.
username - Our xampp or wamp default username is root.
password - Our xampp or wamp default password is blank(no password).
databasename - Our database name is pizza.

You need to add below code to our process.php.

<?php
$con = mysqli_connect('localhost','root','','pizza') or die(mysqli_error());
$sql="INSERT INTO `order` (`name`, `address`, `quantity`) VALUES ('$cus_name', '$address', '$quantity')";
mysqli_query($con,$sql) or die(mysqli_error());
?>


First line will connect to our MySQL sever and it will also return a object which represents the connection to a MySQL Server or FALSE if the connection failed. We need to use this return object in other php function.
In second line, I create a variable of SQL statement that will use in the query function. We can write this SQL statement in the query function directly but we do so for the simplicity. This SQL statement will insert the post data from user order to the order table of our pizza database.
The third line will run our SQL Query.
Our process.php file will be like below.

<?php
 $title = "Pizza Shop: Order Process";
 include('header.php');
 include('sidebar.php');
?>
<div id="content">
<?php
 if(isset($_POST['submit']))
 {
  if( $_POST['cus_name'] != '' && $_POST['quantity'] != '' && $_POST['address'] !='' )
  {
   $cus_name = $_POST['cus_name'];
   $quantity = $_POST['quantity'];
   $address = $_POST['address'];

   $con = mysqli_connect('localhost','root','','pizza') or die(mysqli_error());
   $sql="INSERT INTO `order` (`name`, `address`, `quantity`) VALUES ('$cus_name', '$address', '$quantity')";
   mysqli_query($con,$sql) or die(mysqli_error());
?>
 <p>Thank <?php echo $cus_name; ?> !</p>
 <p>You order <?php echo $quantity; ?> pizza.</p>
 <?php
  $total = $quantity * 10;
 ?>
 <p>It will cost you <?php echo $total; ?> $.</p>
 <p>We will send withing 2 hours to <?php echo $address; ?>.</p>
 <?php
 }
 else
 {
  $_SESSION['error'] = "You need to fill all data";
  header("location: index.php");
 }
 ?>
<?php } ?>
</div><!--end of content -->
<?php
 include('footer.php');
?>
Read more ...

Basic PHP Crash Course (part 5)

Monday, April 9, 2012
This post is part 5 of the Basic PHP Crash Course. If you have never red before this Crash Course, you should read part 1, part 2, part 3 and part 4 first. In this post, we will discuss about our site design or template. For a website it will has header, sidebar, content and footer. So we need to add some html code to our index.php. Following code is our index.php.
<?php session_start(); ?>
<html>
<head>
 <link href="styles.css" rel="stylesheet" type="text/css">
 <title>Pizza Shop: Home</title>
</head>
<body>
 <div id="wrapper">
 <div id="header">
  <h1>Pizza Shop</h1>
 </div><!--end of header -->

 <div id="sidebar">
  <h2>Sidebar</h2>
 </div><!--end of sidebar -->

 <div id="content">
 <?php 
  if($_SESSION['error'] != '')
  {
   echo $_SESSION['error']; 
   $_SESSION['error']='';
  }
 ?>
 <h3>Pizza Shop Order Form</h3>
 <form class="order" action="process.php" method="post">
  <p>
  <label for="cus_name">Customer Name:</label>
  <input type="text" name="cus_name" />
  </p>
  <p>
  <label for="address">Shipping Address:</label>
  <input type="text" name="address" />
  </p>
  <p>
  <label for="quantity">Pizza Quantity:</label>
  <input type="text" name="quantity" />
  </p>
  <p>
  <input type="submit" name="submit" value="Submit Order" />
  </p>
 </form>
 </div><!--end of content -->

 <div id="footer">
  Pizza Shop &copy; 2011
 </div><!--end of footer -->

 </div><!--end of wrapper -->
</body>
</html>
I also create a css file named styles.css like following.
body{
 margin:0px;
 padding:0px;
}
#wrapper{
 width:960px;
 margin:0 auto;
 background-color:#FFC;
}
#header{
 height:90px;
 background-color: #FC0;
}
#header h1{
 color:#FFF;
 padding:10px 0px 0px 10px;
}
#content{
 padding:20px;
 float:left;
}
.order label{
 width:150px;
 float:left;
}
#sidebar{
 width:250px;
 height:300px;
 background-color: #C00;
 float:left;
}
#footer{
 clear:both;
 height:40px;
 background-color:#FC0;
 text-align:center;
}
Now if you run our site, you will see like below.
We have a problem. For our process.php we also need to add the html code that added to our index.php. You can add the needed code to that page. But if you have many files, you need to add every page and if you want to change some code, you will change many files. PHP has a very useful statement include() to solve this problem. It will include and evaluate the specific file. Before we use the include() statement, we will separate the duplicated coed as the separated file. Type the following code and save as header.php.
<?php session_start(); ?>
<html>
<head>
 <link href="styles.css" rel="stylesheet" type="text/css">
 <title>Pizza Shop: Home</title>
</head>
<body>
 <div id="wrapper">

 <div id="header">
  <h1>Pizza Shop</h1>
 </div><!--end of header -->
Type the following code and save as sidebar.php.
<div id="sidebar">
 <h2>Sidebar</h2>
</div><!--end of sidebar -->
Type the following code and save as footer.php.
<div id="footer">
 Pizza Shop &copy; 2011
</div><!--end of footer -->

</div><!--end of wrapper -->
</body>
</html>
Now our index.php will be like below by using include() statement.
<?php
 include('header.php');
 include('sidebar.php');
?>
<div id="content">
<?php 
 if($_SESSION['error'] != '')
 {
  echo $_SESSION['error']; 
  $_SESSION['error']='';
 }
?>
<h3>Pizza Shop Order Form</h3>
<form class="order" action="process.php" method="post">
 <p>
 <label for="cus_name">Customer Name:</label>
 <input type="text" name="cus_name" />
 </p>
 <p>
 <label for="address">Shipping Address:</label>
 <input type="text" name="address" />
 </p>
 <p>
 <label for="quantity">Pizza Quantity:</label>
 <input type="text" name="quantity" />
 </p>
 <p>
 <input type="submit" name="submit" value="Submit Order" />
 </p>
</form>
</div><!--end of content -->
<?php
 include('footer.php');
?>
Our process.php file will be like below.
<?php
 include('header.php');
 include('sidebar.php');
?>
<div id="content">
<?php
 if(isset($_POST['submit']))
 {
  if( $_POST['cus_name'] != '' && $_POST['quantity'] != '' && $_POST['address'] !='' )
  {
   $cus_name = $_POST['cus_name'];
   $quantity = $_POST['quantity'];
   $address = $_POST['address'];
?>
<p>Thank <?php echo $cus_name; ?> !</p>
<p>You order <?php echo $quantity; ?> pizza.</p>
<?php
$total = $quantity * 10;
?>
<p>It will cost you <?php echo $total; ?> $.</p>
<p>We will send withing 2 hours to <?php echo $address; ?>.</p>
<?php
  }
  else
  {
   $_SESSION['error'] = "You need to fill all data";
   header("location: index.php");
  }
?>
<?php } ?>
</div><!--end of content -->
<?php
 include('footer.php');
?>
Our template system is almost finished. Let's think about our page title. It is not flexible. I want to change my title when the page change. To do so we need to create a variable and set our title to this variable before loading the header.php. And then we can use this variable in our header.php. Below is our index.php.
<?php
 $title = "Pizza Shop: Home";
 include('header.php');
 include('sidebar.php');
?>
...
Our process.php file will be like below.
<?php
 $title = "Pizza Shop: Order Process";
 include('header.php');
 include('sidebar.php');
?>
...
Our header.php will be like below.
<?php session_start(); ?>
<html>
<head>
 <link href="styles.css" rel="stylesheet" type="text/css">
 <title><?php echo $title; ?></title>
</head>
<body>
 <div id="wrapper">

 <div id="header">
  <h1>Pizza Shop</h1>
 </div><!--end of header -->
Read more ...

Basic PHP Crash Course (part 4)

Tuesday, April 3, 2012
This post is part 4 of the Basic PHP Crash Course. If you have never red before this Crash Course, you should read part 1, part 2 and part 3 first. In this post we will discuss about PHP Session. It is very useful when you write a web application. Let's think about our pizza shop website. After the user have submitted the order form, our application will call the process.php. Then I want to show the order form again, if the submitted form has the errors. To do so, we have a problem. We cannot know the error data from process.php when we show the order form again. So we must use PHP Session.

What is PHP Session?

Session is a way to store information for the individual user in our server by using session ID. This ID is automatically generated by PHP and store also on the user computer for the lifetime of a session. The content of the session data is store at the server.

Simple Example

<?php session_start(); ?>
<html>
<head>
 <title>Page 1</title>
</head>
<body>
<?php
 $_SESSION['user_name'] = "John";
?>
</body>
</html>
Before we use the session data, we need to load session_start() function. This function will check whether there is already a session. If not, it will create one. Now we can use the superglobal $_SESSION array. So I set the user_name as John. Below is the another page.
<?php session_start(); ?>
<html>
<head>
 <title>Page 2</title>
</head>
<body>
<?php
 echo "Hi ".$_SESSION['user_name'];
?>
</body>
</html>
In this page, we echo the user_name from session data array. If you run the page2, you will see "Hi John". In this way, you can save the data you need for other page. However session data is not permanent storage. For permanent storage, we will use the database like MySql(I will also explain about MySql database later in this series.).

Enhancing our pizza shop website

Now it is time to enhance our pizza shop site. Below is our index.php.
<?php session_start(); ?>
<html>
<head>
 <title>Order Process</title>
</head>
<body>
<?php
 if(isset($_POST['submit']))
 {
  if( $_POST['cus_name'] != '' && $_POST['quantity'] != '' && $_POST['address'] !='' )
  {
   $cus_name = $_POST['cus_name'];
   $quantity = $_POST['quantity'];
   $address = $_POST['address'];
?>
 <p>Thank <?php echo $cus_name; ?> !</p>
 <p>You order <?php echo $quantity; ?> pizza.</p>
<?php
 $total = $quantity * 10;
?>
 <p>It will cost you <?php echo $total; ?> $.</p>
 <p>We will send withing 2 hours to <?php echo $address; ?>.</p>
<?php
 }
 else
 {
  $_SESSION['error'] = "You need to fill all data.";
  header("location: index.php");
 }
?>
<?php } ?>
</body>
</html>
As you know, firstly we need to call the session_start() function to use the session data. If the user submit the form without filling all data, we will set the session error data as "You need to fill all data.". And then redirect our site to index.php by using header() function. This function will tell the browser to load the page that you send as parameter. In our index.php file, we will also start with session_start() function. Then we will retrieve the error data from the session array and will echo before our order form. Below is our index.php.
<?php session_start(); ?>
<html>
<head>
 <title>Pizzs Show: Home</title>
</head>
<body>
<?php 
 if($_SESSION['error'] != '')
 {
  echo $_SESSION['error']; 
  $_SESSION['error']='';
 }
?>
 <h3>Pizza Shop Order Form</h3>
 <form action="process.php" method="post">
 <p>
  <label for="cus_name">Customer Name:</label>
  <input type="text" name="cus_name" />
 </p>
 <p>
  <label for="address">Shipping Address:</label>
  <input type="text" name="address" />
 </p>
 <p>
  <label for="quantity">Pizza Quantity:</label>
  <input type="text" name="quantity" />
 </p>
 <p>
  <input type="submit" name="submit" value="Submit Order" />
 </p>
 </form>
</body>
</html>
Read more ...