backend-01

ref: master

app/daos/UserDAO.php


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php

require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../models/User.php';

class UserDAO {
  private $db;

  public function __construct() {
    $this->db = getDatabaseConnection();
  }

  public function findByEmail($email) {
    $sql = 'SELECT * FROM users WHERE email = :email';

    $stmt = $this->db->prepare($sql);
    $stmt->bindParam(':email', $email);
    $stmt->execute();

    $userData = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($userData) {
      return new User(
        $userData['id'],
        $userData['username'],
        $userData['email'],
        $userData['encrypted_password']
      );
    }

    return null;
  }

  public function create(User $user) {
    $sql = 'INSERT INTO users (username, email, encrypted_password) VALUES (:username, :email, :encrypted_password)';


    $stmt = $this->db->prepare($sql);
    $stmt->bindValue(':username', $user->getUserName());
    $stmt->bindValue(':email', $user->getEmail());
    $stmt->bindValue(':encrypted_password', $user->getEncryptedPassword());
    $stmt->execute();

    $user->setId($this->db->lastInsertId());

    return $user;
  }
}