User Authentication using REST API and JSON Web Tokens (JWT) – Step 3

User Authentication using REST API and JSON Web Tokens (JWT) – Step 3

Create the user object class

  • Create the objects folder inside api folder and create a new file called user.php

<?php

// ‘user’ object

class User

{

    private $conn;

    private $table = “register”;

    // object properties

    public $id;

    public $name;

    public $email;

    public $password;

    public function __construct($db)

    {

        $this->conn = $db;

    }

    public function create()

    {

        $this->name = htmlspecialchars(strip_tags($this->name));

        $this->email = htmlspecialchars(strip_tags($this->email));

        $this->password = htmlspecialchars(strip_tags($this->password));

        $this->password = password_hash($this->password, PASSWORD_DEFAULT);

        $query = “insert into ” . $this->table . ” (name,email,password) values(?,?,?)”;

        try {

            $stmt = $this->conn->prepare($query);

            $run = $stmt->execute([$this->name, $this->email, $this->password]);

            return true;

        } catch (PDOException $exception) {

            if ($exception->getCode() === ‘23000’) {

                echo json_encode(array(“Duplicate Entry” => $this->email . ” already exists”));die;

            } else {

                echo json_encode(array(“insertDataSQLError” => $exception->getMessage()));die;

            }

        }

    }

}

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*