Angular 4 POST for MYSQL database using PHP

I searched for two weeks to find the answer to my question, which, in my opinion, should be relatively simple, but I did not use the right keywords. I know that Angular is a front-end environment, and I can use any database and backend that I would like.

For a school project, I am creating an Ionic 3 / Angular 4 application with a MySQL database, and one of the tasks is requesting a login / registration system. Although there are many tutorials in Firebase, I have not seen any revolving around MySQL.

My main question is: how to configure register.ts file to run the PHP file on the server and transfer data such as name, username, email address and password? We learned basic PHP at school, although I am open to using Node / Mongo, if there is a useful quick start, we are not allowed to use any BaaS such as Firebase.

Here is the code: register.ts file

import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

/**
 * Generated class for the RegisterPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

let user_id: any;
let headers = new Headers(
  {
    'Content-Type' : 'application/x-www-form-urlencoded'
  });





@IonicPage()
@Component({
  selector: 'page-register',
  templateUrl: 'register.html',
})
export class RegisterPage {

  @ViewChild('username') username;
  @ViewChild('email') email;
  @ViewChild('firstname') firstname;
  @ViewChild('password') password;
  @ViewChild('confirmpass') confirmpass;
  //successfully gets this data from the form on the HTML register page


  constructor(public navCtrl: NavController, public navParams: NavParams, public alertCtrl: AlertController, public http: Http) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad RegisterPage');
  }

registerUser() {
  //runs this when register button is pressed
  //bad validation, but what can ya do 
  if (this.password.value != this.confirmpass.value) {
    console.log("confirm pass and password don't match");
    let confirm = this.alertCtrl.create({
    title: 'Sorry!',
    message: 'Password & Confirm Password do not match',
    buttons: [
        {
          text: 'Okay',
          handler: () => {
            console.log('Disagree clicked');
          }
        }
      ]
    });
    confirm.present();
  } else {
//this is where I'm struggling
  let url: string = 'mySchoolsDB.com/myuser/insertuser.php';
  let responseData: any;
  let userData = {"firstname": this.firstname.value, "username": this.username.value, "password": this.password.value, "email": this.email.value };
    console.log('would register user with', this.username.value, this.password.value);

   console.log(userData);
    this.http.post(url, userData, {headers:headers, method:"POST"})
    .map(res => res.json())
    .subscribe(
        data => {
          console.log(data);
        },
        err => {
          console.log("ERROR!: ", err);
        }
    );
  }
}



}

insertuser.php

<?php

header('Access-Control-Allow-Origin: *');

$servername = "db.school.edu";
$dbusername = "myuser";
$dbpassword = "mypass";
$dbname = "mydbname";


$firstname = $_POST['firstname'];
$password = $_POST['password'];
$username = $_POST['username'];
$email = $_POST['email'];
// Create connection
$conn = mysqli_connect($servername, $dbusername, $dbpassword, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
} 

$sql = "INSERT INTO users (firstname, email, username, password)
VALUES ('$firstname', '$email', '$username', '$password')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error:  " . $sql . "<br>" . mysqli_error($conn);
} 

mysqli_close($conn);
?>
+4
source share
1 answer

Here are two lines you need to change

First change:

let headers = new Headers({'Content-Type' : 'application/x-www-form-urlencoded'});

to:

let headers = new Headers({'Content-Type': 'application/json'});

Second

Edit

this.http.post(url, userData, {headers:headers, method:"POST"})

To:

this.http.post(url, userData, {headers}).map(...)....
+1
source

Source: https://habr.com/ru/post/1689659/


All Articles