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

Asked

Viewed 592 times

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 the 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 in the bd the username as Unique thinking it would return some error, but still missing something in my implementation. How and where I should check if the username already exists?

1 answer

0


You have to make a SELECT in the database to check if the username exists, if it does not exist 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;
}
  • I made the changes but now returns to my console: "Blocked cross-origin request: Same Origin Policy (Same Origin Policy) prevents reading the remote resource at http://localhost/api/api.php. (Reason: CORS header 'Access-Control-Allow-Origin' is not present)." I already have in my header: header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8");

  • That I do not understand, but there is something here in Marcelo’s answer in this post https://cursos.alura.com.br/forum/topico-requisicao-cross-origin-blocked

  • You can also search here at this page by Requisição cross-origin bloqueada that you must find some solution to your case

Browser other questions tagged

You are not signed in. Login or sign up in order to post.