PHP REST API CRUD – Step 4

PHP REST API CRUD – Step 4

Step 4 Create user

  • Create the objects folder inside api folder and create a new file called user.php
<?php
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 *

*

*