Save Angular 6 Form Data in Mysql Database

·

,
Angular 6 Material Datatables example with Php Mysql data

Hello to all, welcome to therichpost.com. In this post, I will tell you, Save Angular 6 Form Data in Mysql Database. 

With Angular 6, we will use HTTPCLIENT module to save form fields data into PHP MYSQL. This is very interesting and useful post by my point of view.

Also in it, I covered  with form validation part and this is helpful.

angular6-form-validation

Angular 6 is getting more popularity day by day because of its fantastic features and today I am sharing one of the most important HTTPCLIENT feature.

Here are the following steps need to do for Save Angular 6 Form Data in Mysql Database:
 1. First this is the code for app.module.ts file:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
  BrowserAnimationsModule,
  ReactiveFormsModule,
  HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
 2. After that, add below code into app.component.ts file:
import {Component} from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClient, HttpParams } from '@angular/common/http';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'my-angular-app';
  registerForm: FormGroup;
  submitted = false;

    constructor(private formBuilder: FormBuilder, private http: HttpClient) { }

    ngOnInit() {
        this.registerForm = this.formBuilder.group({
            firstName: ['', Validators.required],
            lastName: ['', Validators.required],
            email: ['', [Validators.required, Validators.email]],
            password: ['', [Validators.required, Validators.minLength(6)]]
        });
    }

    // convenience getter for easy access to form fields
    get f() { return this.registerForm.controls; }
   posts: any;
    onSubmit() {
        this.submitted = true;

        // stop here if form is invalid
        if (this.registerForm.invalid) {
            return;
        }
    // Initialize Params Object
    let Params = new HttpParams();

    // Begin assigning parameters
    Params = Params.append('firstParameter', this.registerForm.value.firstName);
    Params = Params.append('secondParameter', this.registerForm.value.lastName);
    return this.http.get('http://localhost/mypage.php'
    ,{
    params: { params: Params }
    }).subscribe(data => {
      this.posts = data;
      // show data in console
      console.log(this.posts);
      });

      
    }
  
}
 3. After that add below code into your app.component.html file:
<div class="jumbotron">
    <div class="container">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <h3> Welcome to {{ title }}!</h3>
                <form [formGroup]="registerForm" (ngSubmit)="onSubmit()">
                    <div class="form-group">
                        <label>First Name</label>
                        <input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.firstName.errors }" />
                        <div *ngIf="submitted && f.firstName.errors" class="invalid-feedback">
                            <div *ngIf="f.firstName.errors.required">First Name is required</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Last Name</label>
                        <input type="text" formControlName="lastName" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.lastName.errors }" />
                        <div *ngIf="submitted && f.lastName.errors" class="invalid-feedback">
                            <div *ngIf="f.lastName.errors.required">Last Name is required</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Email</label>
                        <input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.email.errors }" />
                        <div *ngIf="submitted && f.email.errors" class="invalid-feedback">
                            <div *ngIf="f.email.errors.required">Email is required</div>
                            <div *ngIf="f.email.errors.email">Email must be a valid email address</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Password</label>
                        <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
                        <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
                            <div *ngIf="f.password.errors.required">Password is required</div>
                            <div *ngIf="f.password.errors.minlength">Password must be at least 6 characters</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <button class="btn btn-primary">Submit</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
4. Finally here is the php file mypage.php code to save Angular 6 Form data and I am just sharing the output receive form Angular 6: 
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
$conn = new mysqli('localhost','root','root','user');
$myArr = array();
$myArr[] = $_GET['params'];
$myJSON = json_encode($myArr);
echo $myJSON;
?>

 

 

And you are done. If you have any query related to this post then you can ask questions or comment below.

Comments

24 responses to “Save Angular 6 Form Data in Mysql Database”

  1. Justina Ng Avatar
    Justina Ng

    nice and awesome post sir. Please sir can you do article on how display database records using php and angular 6

    Thanks

  2. Ajay Malhotra Avatar

    Thank you and sure, I will make post on your request. 🙂

  3. Ajay Malhotra Avatar

    Hi, you can check this post:
    https://therichpost.com/angular-6-material-datatables-example-with-php-mysql-data

    In this post, I am getting data from mysql.

  4. revathi Avatar
    revathi

    params: { params: Params }
    ihave error in this line

  5. revathi Avatar
    revathi

    params: { params: Params }
    params i don’t understand i have error in this line

  6. Ajay Malhotra Avatar

    Can you please tell me the error or I think, there must be undefined parameter in the list.

  7. sayali Avatar
    sayali

    i am new in angular ,can u tell me where can i save that mypage.php file

  8. Ajay Malhotra Avatar

    Hi Sayali, you can place this into your Htdocs folder.

  9. sai Avatar
    sai

    I got the same error, please take a look at it. I am using angular 8
    {
    Type ‘{ params: HttpParams; }’ is not assignable to type ‘HttpParams | { [param: string]: string | string[]; }’.
    Type ‘{ params: HttpParams; }’ is not assignable to type ‘{ [param: string]: string | string[]; }’.
    Property ‘params’ is incompatible with index signature.
    Type ‘HttpParams’ is not assignable to type ‘string | string[]’.
    Type ‘HttpParams’ is missing the following properties from type ‘string[]’: length, pop, push, concat, and 24 more.ts(2322)
    http.d.ts(1090, 9): The expected type comes from property ‘params’ which is declared
    }

  10. Ajay Malhotra Avatar

    Hi Sai, I will update this you tomorrow.

    Thank you

  11. sai Avatar
    sai

    Thank you

  12. Akhil ashok Avatar
    Akhil ashok

    can you please post the css file of this codee

  13. Ajay Malhotra Avatar

    you want that for form styling?

  14. Divya Avatar
    Divya

    Can you please tell how you created table in localhost/phpmyadmin?

  15. Ajay Malhotra Avatar

    It is very simple. go to localhost/phpmyadmin and first create new database then create tables in that database.

  16. Satish Derle Avatar
    Satish Derle

    Dear Sir,

    I am new to Angular and just started the learning. You post is really helpful to new bees. I have question, why you taking help of php to save data to database. Will you post this code for using Express/REST APIs. Or please give link for the sam.

    Thanking you Sir. Please keep coding for new learners.

    -Satish

  17. Ajay Malhotra Avatar

    Yes sure and I have one youtube channel also so please subscribe that also, you will also learn a lot from there.
    https://youtu.be/v5bWJ4TVpeg

  18. V. Senthilkumar Avatar
    V. Senthilkumar

    Hi Ajay, i have placed this into my Htdocs folder, but still i getting this same error

  19. mayur Avatar
    mayur

    No overload matches this call.
    The last overload gave the following error.
    Type ‘HttpParams’ is not assignable to type ‘string | string[]’.
    Type ‘HttpParams’ is missing the following properties from type ‘string[]’: length, pop, push, concat, and 24

  20. Pushpanjali Avatar
    Pushpanjali

    Hey! How I can create this using filezilla server.

  21. Ajay Malhotra Avatar

    Can you please explain it better.

  22. Amir Shahazad Avatar
    Amir Shahazad

    i used this example which working well but when i want to upload image using multer on cloudinary with nodejs backend then form data is not saving into mongodb database can you please add example to upload image on multer with other form data like (usename , address and image of user).
    Thank you sir

  23. Ajay Malhotra Avatar

    Yes sure and thanks.