mini proget angular and php: newsfeed manager.

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

Register form:

Our registry form allows you to add a new user in a database. It is composed of 8 fields: firstname, lastname, email, username, job, password, image cover, user image.

So we'll do this following uses case:

  • create angular form register with validation
  • create form register in html code with validation
  • send our form register to the php server using angular httpclient
  • cheking our form register in the php script.

1. create angular form register with validation

First we import the necessary angular libraries. for that take the component [register.component.ts]:

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

Next, we need to create our form login with validation in [register.component.ts] component:

export class RegisterComponent implements OnInit {
  
  imgProfileSrc: any;	
  imgUserSrc: any;
  isFormSubmited = false;
  serverErrorMessage: string;
  isUserRegistred = true;
  registerForm = new FormGroup({
    	'firstname': new FormControl('',[
    			Validators.required
    		]),
    	'lastname': new FormControl('',[
    			Validators.required
    		]),
    	'email': new FormControl('',[
    			Validators.required,
    			Validators.email
    		]),
    	'job': new FormControl('',[
    			Validators.required,
    		]),
    	'username': new FormControl('',[
    			Validators.required,
    		]),
    	'password': new FormControl('',[
    			Validators.required,
    		]),
    	'coverimg': new FormControl('',[
    			Validators.required,
    		]),
    	'userimg': new FormControl('',[
    			Validators.required,
    		]),
  	});	
}
                    

This html code from our form register in [register.component.html] file:

<form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
    <div *ngIf="(firstname.errors && firstname.dirty)">
                        <small  *ngIf="firstname.errors.required"
                        class="form-text text-muted">
                          <span style="color: red">
                            user name required.
                          </span>
                        </small>
                </div>
                <div *ngIf="(firstname.valid)">
                        <small class="form-text text-muted">
                          <span style="color: green">
                            Valid
                          </span>
                        </small>
                </div>
				<div class="input-group mb-3" 
					[class.input_error]="firstname.invalid && firstname.dirty"
					[class.input_valid]="firstname.valid && firstname.dirty"
					[class.input_init]="!firstname.dirty">
					<input type="text" class="form-control" placeholder="First name"
					formControlName="firstname"/>
					<div class="input-group-prepend">
						<span class="input-group-text" id="basic-addon1">
							<i class="fa fa-user"
							[class.fa_error]="firstname.invalid && firstname.dirty"
							[class.fa_valid]="firstname.valid && firstname.dirty"
							></i>
						</span>
					</div>
				</div>
</form>
                    

We will not take all the html code of form register, you find all the source code with the code source of the proget.

2. send our form register to the php server using angular httpclient:

Now we will send our form registe to the php server, to start it by importing the following libraries on the file [register.component.ts]

import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';

export class RegisterComponent implements OnInit {
    onSubmit(){
    this.isFormSubmited = true;
    let params = new FormData();
    params.append('firstname',this.registerForm.get('firstname').value);
    params.append('lastname',this.registerForm.get('lastname').value);
    params.append('email',this.registerForm.get('email').value);
    params.append('job',this.registerForm.get('lastname').value);
    params.append('username',this.registerForm.get('username').value);
    params.append('password',this.registerForm.get('password').value);
    params.append('userimg',this.registerForm.get('userimg').value);
    params.append('coverimg',this.registerForm.get('coverimg').value);
    this.http.post("http://127.0.0.1/newsfeed_php_project/register.php",params)
            .subscribe(response => {
                if(response["status"] === "success"){
                    this.router.navigate(['/profile/'+response['token']]);
                } 
                if(response["status"] === "error"){
                   this.isFormSubmited = false;
                   this.serverErrorMessage = response["error"];
                   this.isUserRegistred = false;
                }                     
            });
  }
}                        
                    

3. cheking our form register in the php script.

The php of form register script is used to add the user in question in the database, and sends a request to the angular client.

the following php code in [register.php] file:

<?php

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

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

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$job = $_POST['job'];
$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];
$token = md5($username.$email.$password);

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

// save user cover image file
    $coverimg = $target_dir . basename($_FILES["userimg"]["name"]);
    move_uploaded_file($_FILES["userimg"]["tmp_name"], $coverimg);
    $imguserSRC = "http://127.0.0.1/".basename($_FILES["userimg"]["name"]);
    
try{
    $conn = new PDO("mysql:host=$servername;dbname=newsfeed", $username_db, $password_db);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO `user` (`id`, `firstname`, "
            . "`lastname`, `job`, `email`, `username`, "
            . "`password`, `userimg`, `coverimg`, `token`)"
            . " VALUES (NULL, '$firstname', '$lastname', "
            . "'$job', '$email', '$username', '$password', "
            . "'$imguserSRC', '$imgcoverSRC', '$token')";
    $conn->exec($sql);
    $res = [
        'status' => 'success',
        'token' => $token
    ];
    echo json_encode($res);
} catch (Exception $ex) {
    $res = [
        'status' => 'error',
        'error' => $ex->getMessage()
    ];
    echo json_encode($res);
}