Check if a username already exists in angular database 2 + php

0

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?

    
asked by anonymous 31.05.2018 / 22:14

1 answer

0

You have to do a SELECT in the database to check if the username exists, if it does not exist, it does INSERT

$username=$user['username'];

$result = $mysqli->query("SELECT COUNT(*) FROM users WHERE username = '$username'");

$row = $result->fetch_row();

if ($row[0] > 0) {
    //já existe
} else {
    $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;
}
    
01.06.2018 / 02:04