Mini proget Angular and PHP with source code: form wizard validation

if you want help, please contact us in our email:
mouhamed_ali_derwich@webi4u.com
if you want help, please contact us in our email:
mouhamed_ali_derwich@webi4u.com

Introduction:

With this guide, we will learn how to make a step by step form with validation, using Angular and PHP. For this, we will touch different techniche in Angular and php such as:

  • How to create an Angular form with validation.
  • How to submit an Angular form with multipar data.
  • How to save a form in database using php and MySql.
  • Using Angular routing system.
  • Using Angular Httpclient API.
prerequisites

to get started, you need to have the following skills:

  • HTML, CSS, BOOTSTRAP, JQUERY
  • Angular
  • PHP
  • MySql

1. Project Setup

our mini project consists of two parts, the Angular part, and the PHP part. let's start with the configuration of the angular part.

First we will create the angular proget using angular CLI:

ng new form-wizard-validation

Next, we need to create seven angular components for our proget:

ng generate component form-account-information
ng generate component form-bank-information
ng generate component form-check-information
ng generate component form-personal-information
ng generate component login
ng generate component user-profile

We need to create our database on MySql. For this go to phpmyadmin to generate a new database name: [ form-wizard ] and create the USER table using the following SQL code.

CREATE TABLE `USER` (
  `id` int(11) NOT NULL,
  `username` varchar(80) NOT NULL,
  `password` varchar(20) NOT NULL,
  `firstname` varchar(80) NOT NULL,
  `lastname` varchar(80) NOT NULL,
  `phone` varchar(20) NOT NULL,
  `adress` varchar(100) NOT NULL,
  `zibcode` int(11) NOT NULL,
  `state` varchar(100) NOT NULL,
  `country` varchar(100) NOT NULL,
  `datebirth` varchar(80) NOT NULL,
  `gender` varchar(50) NOT NULL,
  `bankname` varchar(100) NOT NULL,
  `branchename` varchar(100) NOT NULL,
  `accountname` varchar(100) NOT NULL,
  `accountcreated` varchar(50) NOT NULL,
  `discribe` varchar(150) NOT NULL,
  `imgprofile` varchar(255) NOT NULL,
  `imgcover` varchar(255) NOT NULL,
  `facebook` varchar(150) NOT NULL,
  `twitter` varchar(150) NOT NULL,
  `linkedin` varchar(150) NOT NULL,
  `email` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
                    

2. form account information

We will start now to develop our form wizard, let's start with the form account step.

the form account step consists of three fields:

  • user name
  • email adress
  • password
a- create angular form:

import this package in [ FormAccountInformationComponent ]

import { FormGroup, FormControl, Validators } from '@angular/forms';
                    

create the angular form with validation in [ FormAccountInformationComponent ]:

export class FormAccountInformationComponent implements OnInit {
   formAccount = new FormGroup({
        'email': new FormControl('',[
                Validators.email,
                Validators.required
            ]),
        'userName': new FormControl('',[
                Validators.required
            ]),
        'password': new FormControl('',[
                Validators.required,
                Validators.minLength(8),
                Validators.maxLength(12),
            ]),
    })
}
                    

form account html code in fille [form-account-information.component.html]

We will not take all the field form of our account form because all are develop according to the same principle.

<form [formGroup]="formAccount" (ngSubmit)="onSubmit()"
          <div class="form-group row">
                      <label for="staticEmail" class="col col-form-label">
                        Email
                      </label>
                  <div>
                    <input type="email" formControlName="email"  class="form-control"
                    [class.input_error]="email.invalid && email.dirty"
                    [class.input_valid]="email.valid && email.dirty"/>
                    <div *ngIf="(email.errors && email.dirty)">
                        <small  *ngIf="email.errors.required"
                        class="form-text text-muted">
                          <span style="color: red">
                            Adress email required.
                          </span>
                        </small>
                        <small  *ngIf="email.errors.email"
                        class="form-text text-muted">
                          <span style="color: red">
                            Adress email not valid.
                          </span>
                        </small>
                    </div>
                  </div>
                  </div>
</form>                      
                

form account submit event:

create new service in your angular component:

ng generate service user

the role of user service is to store the information of all the forms, before it is sent to the PHP server

to finish with [ user service ], copy this code in [ user.service.ts ]

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {
    email: string;
    username : string;
    password: string;
    firstname: string;
    lastname: string;
    phone: string;
    adress: string;
    zibcode: string;
    state: string;
    contry: string;
    datebirth: string;
    gender: string;
    bankname: string;
    branchename: string;
    accountname: string;
    accountcreated: string;  
    discribe: string;
    imgprofile: any;
    imgcover: any;
    imgProfileBase64: any;
    imgCoverBase64: any;
    facebook: string;
    twitter: string;
    linkedin: string;
  constructor() { }
}                    
                

Import the user service in [ form-account-information.component ]

import { UserService } from '../user.service';                    
                

Inject the user service in [ form-account-information.component ]

constructor(
    private user: UserService) { 
  }                   
                

Now this is the code of submit event in [ form-account-information.component ]

onSubmit(){
    if(this.formAccount.status != "INVALID"){
        this.user.email = this.formAccount.get('email').value;
        this.user.username = this.formAccount.get('userName').value;
        this.user.password = this.formAccount.get('password').value;
        this.router.navigate(['/step-two']);
    }
 }                    
                

We will not take all form of our mini proget, because all are develop according to the same principle.

PHP code of our mini proget

Finally, we take care to record all the information on a database MySql, using php. Here is all the php code:

<?php 
header("Access-Control-Allow-Origin: *");
header("Content-type:application/json");

$servername = "localhost";
$username_db = "root";
$password_db = "root";

$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$phone = $_POST['phone'];
$adress = $_POST['adress'];
$zibcode = $_POST['zibcode'];
$state = $_POST['state'];
$contry = $_POST['contry'];
$datebirth = $_POST['datebirth'];
$gender = $_POST['gender'];
$bankname = $_POST['bankname'];
$branchename = $_POST['branchename'];
$accountname = $_POST['accountname'];
$accountcreated = $_POST['accountcreated'];  
$discribe = $_POST['discribe'];
$imgprofile = $_POST['imgprofile'];
$imgcover = $_POST['imgprofile'];
$facebook = $_POST['facebook'];
$twitter = $_POST['twitter'];
$linkedin = $_POST['linkedin'];

$target_dir = "/var/www/html/";
// save user image file
    $imgprofile = $target_dir . basename($_FILES["imgprofile"]["name"]);
    move_uploaded_file($_FILES["imgprofile"]["tmp_name"], $imgprofile);

// save user cover image file
    $coverimg = $target_dir . basename($_FILES["imgcover"]["name"]);
    move_uploaded_file($_FILES["imgcover"]["tmp_name"], $coverimg);    

try {
    $conn = new PDO("mysql:host=$servername;dbname=form-wizard", $username_db, $password_db);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO `USER` "
            . "(`id`, `username`, `password`, "
            . "`firstname`, `lastname`, `phone`, "
            . "`adress`, `zibcode`, `state`, `country`, "
            . "`datebirth`, `gender`, `bankname`, `branchename`, "
            . "`accountname`, `accountcreated`, `discribe`, `imgprofile`,"
            . " `imgcover`, `facebook`, `twitter`, `linkedin`) "
            . "VALUES (NULL, '$email', '$password', '$firstname', '$lastname', "
            . "'$phone', '$adress', '$zibcode', '$state', '$contry', "
            . "'$datebirth', '$gender', '$bankname', '$branchename', "
            . "'$accountname', '$accountcreated', '$discribe', '$imgprofile', "
            . "'$coverimg', '$facebook', '$twitter', '$linkedin');";
    $conn->exec($sql);
        $res = ['status' => 'yes'];
        echo json_encode($res);
    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
        $res = [
            'status' => 'not',
            'message' => $e->getMessage()
            ];
    }