I need to check if a user already exists before registering.
I have the following methods:
register.component.ts:
import { AlertService } from './../alert.service';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { UserService } from '../user.service';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent{
model: any = {};
loading = false;
constructor(private router: Router,
private userService: UserService,
private alertService: AlertService) { }
register(){
this.loading = true;
this.userService.create(this.model)
.subscribe(
data => {
console.log(data);
this.alertService.success('Registro realizado com sucesso!', true);
},
error => {
this.alertService.error(error);
this.loading = false;
});
}
}
My method in user service:
create(user: Usuario) {
return this.http.post('http://localhost/api/api.php', JSON.stringify(user));
}
My api:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password,'mydb');
$user = json_decode(file_get_contents('php://input'),true);
if(isset($user['username'])){
$sql = "INSERT INTO users (first_name, last_name, username,password)
VALUES ('".$user['firstName']."', '".$user['lastName']."', '".$user['username']."','".$user['password']."')";
mysqli_query($conn, $sql);
echo json_encode(array('response'=>'sucess'));die;
}
mysqli_close($conn);
?>
I put the username as unique thinking that it would return some error, but something is missing in my implementation. How and where should I check if the username already exists?