Mysql
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Mysql

Quản lý tài khoản người dùng, vai trò, quyền, xác thực PHP và MySQL - Phần 4

Đây là phần 4 của loạt bài về cách tạo hệ thống quản lý tài khoản người dùng bằng PHP. Bạn có thể tìm các phần khác tại đây:part1, part2, part 3.

Cho đến nay, chúng tôi đã bao gồm đăng ký người dùng và đăng nhập cho khu vực công cộng. Người dùng quản trị viên có thể đăng nhập ngay cả như bây giờ nhưng chúng tôi vẫn chưa làm việc để tạo tài khoản người dùng quản trị viên. Ngoài ra, nếu bạn chỉ cần nhập http://localhost/user-accounts/admin/dashboard.php trên trình duyệt, bạn có thể truy cập vào phần quản trị viên mà không cần phải là người dùng quản trị viên. Nhưng chúng tôi sẽ sớm khắc phục tất cả những điều đó.

Trong phần này, chúng ta sẽ tạo, cập nhật tài khoản người dùng quản trị. Chúng tôi cũng sẽ xác minh rằng mật khẩu cũ khớp trước khi cập nhật tài khoản người dùng.

Bên trong thư mục admin / users, hãy tạo 3 tệp sau:

  1. userForm.php:Chứa biểu mẫu để tạo và chỉnh sửa tài khoản người dùng.
  2. userList.php:Liệt kê tất cả người dùng quản trị trên hệ thống.
  3. userLogic.php:Theo cách nói của MVC (Model-View-Controller), chúng ta có thể coi đây là bộ điều khiển người dùng. Nó chứa các logic như nhận thông tin người dùng từ biểu mẫu, lưu vào cơ sở dữ liệu, truy xuất lại, thao tác với nó, v.v.

Hãy bắt đầu với userForm.php. Mở nó ra và dán mã này vào đó.

userForm.php:

<?php include('../../config.php'); ?>
<?php include(INCLUDE_PATH . '/logic/common_functions.php') ?>
<?php include(ROOT_PATH . '/admin/users/userLogic.php'); ?>
<?php $roles = getAllRoles(); ?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>UserAccounts - Create Admin user Account</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <!-- Custome styles -->
    <link rel="stylesheet" href="../../assets/css/style.css">
  </head>
  <body>
    <?php include(INCLUDE_PATH . "/layouts/admin_navbar.php") ?>
    <div class="container" style="margin-bottom: 150px;">
      <div class="row">
        <div class="col-md-4 col-md-offset-4">
          <a href="userList.php" class="btn btn-primary" style="margin-bottom: 5px;">
            <span class="glyphicon glyphicon-chevron-left"></span>
            Users
          </a>
          <br>

          <form class="form" action="userForm.php" method="post" enctype="multipart/form-data">
            <?php if ($isEditing === true ): ?>
              <h2 class="text-center">Update Admin user</h2>
            <?php else: ?>
              <h2 class="text-center">Create Admin user</h2>
            <?php endif; ?>
            <hr>
            <!-- if editting user, we need that user's id -->
            <?php if ($isEditing === true): ?>
              <input type="hidden" name="user_id" value="<?php echo $user_id ?>">
            <?php endif; ?>
            <div class="form-group <?php echo isset($errors['username']) ? 'has-error' : '' ?>">
              <label class="control-label">Username</label>
              <input type="text" name="username" value="<?php echo $username; ?>" class="form-control">
              <?php if (isset($errors['username'])): ?>
                <span class="help-block"><?php echo $errors['username'] ?></span>
              <?php endif; ?>
            </div>
            <div class="form-group <?php echo isset($errors['email']) ? 'has-error' : '' ?>">
              <label class="control-label">Email Address</label>
              <input type="email" name="email" value="<?php echo $email; ?>" class="form-control">
              <?php if (isset($errors['email'])): ?>
                <span class="help-block"><?php echo $errors['email'] ?></span>
              <?php endif; ?>
            </div>
            <?php if ($isEditing === true ): ?>
              <div class="form-group <?php echo isset($errors['passwordOld']) ? 'has-error' : '' ?>">
                <label class="control-label">Old Password</label>
                <input type="password" name="passwordOld" class="form-control">
                <?php if (isset($errors['passwordOld'])): ?>
                  <span class="help-block"><?php echo $errors['passwordOld'] ?></span>
                <?php endif; ?>
              </div>
            <?php endif; ?>
            <div class="form-group <?php echo isset($errors['password']) ? 'has-error' : '' ?>">
              <label class="control-label">Your Password</label>
              <input type="password" name="password" class="form-control">
              <?php if (isset($errors['password'])): ?>
                <span class="help-block"><?php echo $errors['password'] ?></span>
              <?php endif; ?>
            </div>
            <div class="form-group <?php echo isset($errors['role_id']) ? 'has-error' : '' ?>">
              <label class="control-label">User Role</label>
              <select class="form-control" name="role_id">
                <option value="" ></option>
                <?php foreach ($roles as $role): ?>
                  <?php if ($role['id'] === $role_id): ?>
                    <option value="<?php echo $role['id'] ?>" selected><?php echo $role['name'] ?></option>
                  <?php else: ?>
                    <option value="<?php echo $role['id'] ?>"><?php echo $role['name'] ?></option>
                  <?php endif; ?>
                <?php endforeach; ?>
              </select>
              <?php if (isset($errors['role_id'])): ?>
                <span class="help-block"><?php echo $errors['role_id'] ?></span>
              <?php endif; ?>
            </div>
            <div class="form-group" style="text-align: center;">
              <?php if (!empty($profile_picture)): ?>
                <img src="<?php echo BASE_URL . '/assets/images/' . $profile_picture; ?>" id="profile_img" style="height: 100px; border-radius: 50%" alt="">
              <?php else: ?>
                <img src="http://via.placeholder.com/150x150" id="profile_img" style="height: 100px; border-radius: 50%" alt="">
              <?php endif; ?>
              <input type="file" name="profile_picture" id="profile_input" value="" style="display: none;">
            </div>
            <div class="form-group">
              <?php if ($isEditing === true): ?>
                <button type="submit" name="update_user" class="btn btn-success btn-block btn-lg">Update user</button>
              <?php else: ?>
                <button type="submit" name="save_user" class="btn btn-success btn-block btn-lg">Save user</button>
              <?php endif; ?>
            </div>
          </form>
        </div>
      </div>
    </div>
  <?php include(INCLUDE_PATH . "/layouts/footer.php") ?>
<script type="text/javascript" src="../../assets/js/display_profile_image.js"></script>

Nếu chúng tôi mở trang này trong trình duyệt của mình tại http://localhost/user-accounts/admin/users/userForm.php, chúng tôi sẽ thấy một thông báo lỗi cho biết chúng tôi đang gọi một phương thức không xác định getAllRoles (). Chúng ta cần phương pháp này vì để tạo người dùng quản trị, chúng ta cần chọn một vai trò từ danh sách tất cả các vai trò trong cơ sở dữ liệu để gán cho người dùng này. Vì vậy, chúng tôi sẽ nhận tất cả các vai trò từ cơ sở dữ liệu và điền chúng vào một trường chọn tùy chọn trong biểu mẫu.

Chúng tôi sẽ tạo phương thức này bên trong tệp userLogic.php. Như vậy:

userLogic.php:

<?php
  // variable declaration. These variables will be used in the user form
  $user_id = 0;
  $role_id = NULL;
  $username = "";
  $email = "";
  $password = "";
  $passwordConf = "";
  $profile_picture = "";
  $isEditing = false;
  $users = array();
  $errors = array();

  function getAllRoles(){
    global $conn;
    $sql = "SELECT id, name FROM roles";
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $result = $stmt->get_result();
    $roles = $result->fetch_all(MYSQLI_ASSOC);
    return $roles;
  }

Làm mới trên trình duyệt của bạn ngay bây giờ, bạn sẽ thấy rằng lỗi đã biến mất và biểu mẫu của chúng tôi hiện đã sạch ở giữa trang. Tốt!

Nếu bạn nhấp vào menu thả xuống vai trò trên biểu mẫu, bạn sẽ nhận thấy chưa có vai trò nào. Điều này là do chúng tôi đã tạo bảng vai trò trong cơ sở dữ liệu nhưng chúng tôi chưa thêm vai trò vào đó. Sử dụng PHPMyAdmin hoặc bất kỳ ứng dụng khách MySQL nào bạn có, hãy thêm ba vai trò sau vào bảng vai trò trong cơ sở dữ liệu của chúng tôi:Quản trị viên, Người chỉnh sửa và Tác giả.

Hoặc bạn có thể chỉ cần chạy lệnh chèn SQL này để chèn cả ba vai trò cùng một lúc:

INSERT INTO `roles`(`id`, `name`, `description`) 
VALUES  (1, 'Admin', 'Has authority of users and roles and permissions.' ), 
		(2, 'Author', 'Has full authority of own posts'), 
		(3, 'Editor', 'Has full authority over all posts')

Nếu bạn tải lại trang, các vai trò này sẽ có sẵn trong trường chọn vai trò của bạn.

Tại thời điểm này, chúng tôi chưa thể tạo người dùng. Nhưng hình thức là tất cả các thiết lập. Tất cả những gì còn lại là mã nhận các giá trị được gửi bởi biểu mẫu. Chúng tôi sẽ đặt mã này trong tệp userLogic.php. Mở lại một lần nữa và thêm đoạn mã còn lại cần thiết để tạo, cập nhật, chỉnh sửa và xóa người dùng.

userLogic.php:

// ... variables declaration is up here ...
// ACTION: update user
if (isset($_POST['update_user'])) { // if user clicked update_user button ...
    $user_id = $_POST['user_id'];
    updateUser($user_id);
}
// ACTION: Save User
if (isset($_POST['save_user'])) {  // if user clicked save_user button ...
    saveUser();
}
// ACTION: fetch user for editting
if (isset($_GET["edit_user"])) {
  $user_id = $_GET["edit_user"];
  editUser($user_id);
}
// ACTION: Delete user
if (isset($_GET['delete_user'])) {
  $user_id = $_GET['delete_user'];
  deleteUser($user_id);
}

function updateUser($user_id) {
  global $conn, $errors, $username, $role_id, $email, $isEditing;
  $errors = validateUser($_POST, ['update_user', 'update_profile']);

  // receive all input values from the form
  $username = $_POST['username'];
  $email = $_POST['email'];
  $password = password_hash($_POST['password'], PASSWORD_DEFAULT); //encrypt the password before saving in the database
  $profile_picture = uploadProfilePicture();
  if (count($errors) === 0) {
    if (isset($_POST['role_id'])) {
      $role_id = $_POST['role_id'];
    }
    $sql = "UPDATE users SET username=?, role_id=?, email=?, password=?, profile_picture=? WHERE id=?";
    $result = modifyRecord($sql, 'sisssi', [$username, $role_id, $email, $password, $profile_picture, $user_id]);

    if ($result) {
      $_SESSION['success_msg'] = "User account successfully updated";
      header("location: " . BASE_URL . "admin/users/userList.php");
      exit(0);
    }
  } else {
    // continue editting if there were errors
    $isEditing = true;
  }
}
// Save user to database
function saveUser(){
  global $conn, $errors, $username, $role_id, $email, $isEditing;
  $errors = validateUser($_POST, ['save_user']);
  // receive all input values from the form
  $username = $_POST['username'];
  $email = $_POST['email'];
  $password = password_hash($_POST['password'], PASSWORD_DEFAULT); //encrypt the password before saving in the database
  $profile_picture = uploadProfilePicture(); // upload profile picture and return the picture name
  if (count($errors) === 0) {
    if (isset($_POST['role_id'])) {
      $role_id = $_POST['role_id'];
    }
    $sql = "INSERT INTO users SET username=?, role_id=?, email=?, password=?, profile_picture=?";
    $result = modifyRecord($sql, 'sisss', [$username, $role_id, $email, $password, $profile_picture]);

    if($result){
      $_SESSION['success_msg'] = "User account created successfully";
      header("location: " . BASE_URL . "admin/users/userList.php");
      exit(0);
    } else {
      $_SESSION['error_msg'] = "Something went wrong. Could not save user in Database";
    }
  }
}
function getAdminUsers(){
  global $conn;
  // for every user, select a user role name from roles table, and then id, role_id and username from user table
  // where the role_id on user table matches the id on roles table
  $sql = "SELECT r.name as role, u.id, u.role_id, u.username
          FROM users u
          LEFT JOIN roles r ON u.role_id=r.id
          WHERE role_id IS NOT NULL AND u.id != ?";

  $users = getMultipleRecords($sql, 'i', [$_SESSION['user']['id']]);
  return $users;
}

function editUser($user_id){
  global $conn, $user_id, $role_id, $username, $email, $isEditing, $profile_picture;

  $sql = "SELECT * FROM users WHERE id=?";
  $user = getSingleRecord($sql, 'i', [$user_id]);

  $user_id = $user['id'];
  $role_id = $user['role_id'];
  $username = $user['username'];
  $profile_picture = $user['profile_picture'];
  $email = $user['email'];
  $isEditing = true;
}
function deleteUser($user_id) {
  global $conn;
  $sql = "DELETE FROM users WHERE id=?";
  $result = modifyRecord($sql, 'i', [$user_id]);

  if ($result) {
    $_SESSION['success_msg'] = "User trashed!!";
    header("location: " . BASE_URL . "admin/users/userList.php");
    exit(0);
  }
}

Không cần điền vào biểu mẫu, hãy nhấp vào nút 'Lưu người dùng' và bạn sẽ thấy rằng các thông báo xác thực xuất hiện trên biểu mẫu. Chúng tôi đang sử dụng cùng một hàm validateUser () mà chúng tôi đã xác định trước đó. Vì vậy, bạn thấy cách cấu trúc lại mã của chúng tôi thành các phương pháp như vậy giúp chúng tôi không lặp lại mã như thế nào. Ngay cả việc tải lên hình ảnh cũng được xử lý bởi uploadProfileImage () đã được xác định trong một trong các hướng dẫn trước đó.

Hãy tạo người dùng quản trị đầu tiên của chúng tôi. Điền vào biểu mẫu và nhấp vào nút 'Lưu người dùng'. Thao tác này sẽ lưu người dùng Quản trị của chúng tôi trong cơ sở dữ liệu và chuyển hướng đến trang userList.php hiện đang trống.

Tệp userList.php được cho là liệt kê những người dùng quản trị có sẵn trong cơ sở dữ liệu. Vì vậy, hãy viết mã cho điều đó.

userList.php:

<?php include('../../config.php') ?>
<?php include(ROOT_PATH . '/admin/users/userLogic.php') ?>
<?php
  $adminUsers = getAdminUsers();
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Admin Area - Users </title>
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
  <!-- Custome styles -->
  <link rel="stylesheet" href="../../static/css/style.css">
</head>
<body>
  <?php include(INCLUDE_PATH . "/layouts/admin_navbar.php") ?>
  <div class="col-md-8 col-md-offset-2">
    <a href="userForm.php" class="btn btn-success">
      <span class="glyphicon glyphicon-plus"></span>
      Create new user
    </a>
    <hr>
    <h1 class="text-center">Admin Users</h1>
    <br />
    <?php if (isset($users)): ?>
      <table class="table table-bordered">
        <thead>
          <tr>
            <th>N</th>
            <th>Username</th>
            <th>Role</th>
            <th colspan="2" class="text-center">Action</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($adminUsers as $key => $value): ?>
            <tr>
              <td><?php echo $key + 1; ?></td>
              <td><?php echo $value['username'] ?></td>
              <td><?php echo $value['role']; ?></td>
              <td class="text-center">
                <a href="<?php echo BASE_URL ?>admin/users/userForm.php?edit_user=<?php echo $value['id'] ?>" class="btn btn-sm btn-success">
                  <span class="glyphicon glyphicon-pencil"></span>
                </a>
              </td>
              <td class="text-center">
                <a href="<?php echo BASE_URL ?>admin/users/userForm.php?delete_user=<?php echo $value['id'] ?>" class="btn btn-sm btn-danger">
                  <span class="glyphicon glyphicon-trash"></span>
                </a>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php else: ?>
      <h2 class="text-center">No users in database</h2>
    <?php endif; ?>
  </div>
  <?php include(INCLUDE_PATH . "/layouts/footer.php") ?>
</body>
</html>

Trong tệp userLogic.php của chúng tôi từ một lúc trước, chúng tôi đã bao gồm một phương thức được gọi là getAdminUsers (). Phương pháp này chọn tất cả người dùng quản trị từ cơ sở dữ liệu sẽ được hiển thị.

Chỉ cần làm mới trang userList.php trên trình duyệt và thì đấy! Chúng tôi có người dùng Quản trị đầu tiên của chúng tôi được liệt kê trên một bảng. Nhấp vào nút màu xanh lá cây có biểu tượng bút chì để chỉnh sửa người dùng. Bạn cũng có thể nhấp vào nút màu đỏ có biểu tượng thùng rác để xóa người dùng.

Vai trò của Người dùng

Bây giờ chúng ta có thể tạo người dùng của mình và gán vai trò cho họ nhưng nếu chúng ta muốn thêm một vai trò khác vào hệ thống thì sao? Chúng ta không thể dựa vào việc chạy một lệnh trực tiếp trên cơ sở dữ liệu của mình mỗi khi chúng ta muốn tạo một vai trò, phải không? Hãy chỉ kết thúc phần này với Tạo, cập nhật và xóa vai trò.

Điều hướng đến thư mục quản trị / vai trò và tạo ba tệp:roleForm.php, roleList.php và roleLogic.php. (Tương tự với thư mục người dùng, không?)

roleForm.php:

<?php include('../../config.php') ?>
<?php include(ROOT_PATH . '/includes/logic/common_functions.php') ?>
<?php include(ROOT_PATH . '/admin/roles/roleLogic.php') ?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Admin - Create new role </title>
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
  <!-- Custom styles -->
  <link rel="stylesheet" href="../../static/css/style.css">
</head>
<body>
  <?php include(INCLUDE_PATH . "/layouts/admin_navbar.php") ?>
  <div class="col-md-8 col-md-offset-2">
      <a href="roleList.php" class="btn btn-primary">
        <span class="glyphicon glyphicon-chevron-left"></span>
        Roles
      </a>
      <hr>
      <form class="form" action="roleForm.php" method="post">
        <?php if ($isEditting === true): ?>
          <h1 class="text-center">Update Role</h1>
        <?php else: ?>
          <h1 class="text-center">Create Role</h1>
        <?php endif; ?>
        <br />

        <?php if ($isEditting === true): ?>
          <input type="hidden" name="role_id" value="<?php echo $role_id ?>">
        <?php endif; ?>
        <div class="form-group <?php echo isset($errors['name']) ? 'has-error': '' ?>">
          <label class="control-label">Role name</label>
          <input type="text" name="name" value="<?php echo $name; ?>" class="form-control">
          <?php if (isset($errors['name'])): ?>
            <span class="help-block"><?php echo $errors['name'] ?></span>
          <?php endif; ?>
        </div>
        <div class="form-group <?php echo isset($errors['description']) ? 'has-error': '' ?>">
          <label class="control-label">Description</label>
          <textarea name="description" value="<?php echo $description; ?>"  rows="3" cols="10" class="form-control"><?php echo $description; ?></textarea>
          <?php if (isset($errors['description'])): ?>
            <span class="help-block"><?php echo $errors['description'] ?></span>
          <?php endif; ?>
        </div>
        <div class="form-group">
          <?php if ($isEditting === true): ?>
            <button type="submit" name="update_role" class="btn btn-primary">Update Role</button>
          <?php else: ?>
            <button type="submit" name="save_role" class="btn btn-success">Save Role</button>
          <?php endif; ?>
        </div>
      </form>
  </div>
  <?php include(INCLUDE_PATH . "/layouts/footer.php") ?>
</body>
</html>

Điều này rất giống với những gì chúng tôi đã làm trong trường hợp người dùng nên tôi sẽ không giải thích nhiều ở đây. Bây giờ chúng ta tiến tới roleLogic.php nơi chúng ta viết mã cần thiết để tạo, cập nhật và xóa các vai trò.

roleLogic.php:

<?php
  $role_id = 0;
  $name = "";
  $description = "";
  $isEditting = false;
  $roles = array();
  $errors = array();

  // ACTION: update role
  if (isset($_POST['update_role'])) {
      $role_id = $_POST['role_id'];
      updateRole($role_id);
  }
  // ACTION: Save Role
  if (isset($_POST['save_role'])) {
      saveRole();
  }
  // ACTION: fetch role for editting
  if (isset($_GET["edit_role"])) {
    $role_id = $_GET['edit_role'];
    editRole($role_id);
  }
  // ACTION: Delete role
  if (isset($_GET['delete_role'])) {
    $role_id = $_GET['delete_role'];
    deleteRole($role_id);
  }
  // Save role to database
  function saveRole(){
    global $conn, $errors, $name, $description;
    $errors = validateRole($_POST, ['save_role']);
    if (count($errors) === 0) {
       // receive form values
       $name = $_POST['name'];
       $description = $_POST['description'];
       $sql = "INSERT INTO roles SET name=?, description=?";
       $result = modifyRecord($sql, 'ss', [$name, $description]);

       if ($result) {
         $_SESSION['success_msg'] = "Role created successfully";
         header("location: " . BASE_URL . "admin/roles/roleList.php");
         exit(0);
       } else {
         $_SESSION['error_msg'] = "Something went wrong. Could not save role in Database";
       }
    }
  }
  function updateRole($role_id){
    global $conn, $errors, $name, $isEditting; // pull in global form variables into function
    $errors = validateRole($_POST, ['update_role']); // validate form
    if (count($errors) === 0) {
      // receive form values
      $name = $_POST['name'];
      $description = $_POST['description'];
      $sql = "UPDATE roles SET name=?, description=? WHERE id=?";
      $result = modifyRecord($sql, 'ssi', [$name, $description, $role_id]);

      if ($result) {
        $_SESSION['success_msg'] = "Role successfully updated";
        $isEditting = false;
        header("location: " . BASE_URL . "admin/roles/roleList.php");
        exit(0);
      } else {
        $_SESSION['error_msg'] = "Something went wrong. Could not save role in Database";
      }
    }
  }
  function editRole($role_id){
    global $conn, $name, $description, $isEditting;
    $sql = "SELECT * FROM roles WHERE id=? LIMIT 1";
    $role = getSingleRecord($sql, 'i', [$role_id]);

    $role_id = $role['id'];
    $name = $role['name'];
    $description = $role['description'];
    $isEditting = true;
  }
  function deleteRole($role_id) {
    global $conn;
    $sql = "DELETE FROM roles WHERE id=?";
    $result = modifyRecord($sql, 'i', [$role_id]);
    if ($result) {
      $_SESSION['success_msg'] = "Role trashed!!";
      header("location: " . BASE_URL . "admin/roles/roleList.php");
      exit(0);
    }
  }
  function getAllRoles(){
    global $conn;
    $sql = "SELECT id, name FROM roles";
    $roles = getMultipleRecords($sql);
    return $roles;
  }

Nhưng khi bạn nhấp vào nút 'Lưu vai trò', Nó đưa ra cảnh báo về phương thức validateRole () không xác định. Cũng giống như validateUser () cho người dùng, chúng tôi sẽ thêm phương thức validateRole () này vào tệp common_functions.php của chúng tôi. Vì vậy, hãy mở tệp và thêm chức năng này vào cuối tệp.

common_functions.php:

// ... other functions up here ...

// Accept a post object, validates post and return an array with the error messages
function validateRole($role, $ignoreFields) {
    global $conn;
    $errors = [];
    foreach ($role as $key => $value) {
      if (in_array($key, $ignoreFields)) {
          continue;
      }
      if (empty($role[$key])) {
        $errors[$key] = "This field is required";
      }
    }
    return $errors;
}

Nhấp lại vào nút Lưu vai trò và bạn thấy thông báo lỗi hiển thị.

Tiếp theo là tệp roleList.php.

roleList.php:

<?php include('../../config.php') ?>
<?php include(ROOT_PATH . '/admin/roles/roleLogic.php') ?>
<?php
  $roles = getAllRoles();
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Admin Area - User Roles </title>
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
  <!-- Custome styles -->
  <link rel="stylesheet" href="../../static/css/style.css">
</head>
<body>
  <?php include(INCLUDE_PATH . "/layouts/admin_navbar.php") ?>
  <div class="col-md-8 col-md-offset-2">
    <a href="roleForm.php" class="btn btn-success">
      <span class="glyphicon glyphicon-plus"></span>
      Create new role
    </a>
    <hr>
    <h1 class="text-center">User Roles</h1>
    <br />
    <?php if (isset($roles)): ?>
      <table class="table table-bordered">
        <thead>
          <tr>
            <th>N</th>
            <th>Role name</th>
            <th colspan="3" class="text-center">Action</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($roles as $key => $value): ?>
            <tr>
              <td><?php echo $key + 1; ?></td>
              <td><?php echo $value['name'] ?></td>
              <td class="text-center">
                <a href="<?php echo BASE_URL ?>admin/roles/assignPermissions.php?assign_permissions=<?php echo $value['id'] ?>" class="btn btn-sm btn-info">
                  permissions
                </a>
              </td>
              <td class="text-center">
                <a href="<?php echo BASE_URL ?>admin/roles/roleForm.php?edit_role=<?php echo $value['id'] ?>" class="btn btn-sm btn-success">
                  <span class="glyphicon glyphicon-pencil"></span>
                </a>
              </td>
              <td class="text-center">
                <a href="<?php echo BASE_URL ?>admin/roles/roleForm.php?delete_role=<?php echo $value['id'] ?>" class="btn btn-sm btn-danger">
                  <span class="glyphicon glyphicon-trash"></span>
                </a>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php else: ?>
      <h2 class="text-center">No roles in database</h2>
    <?php endif; ?>
  </div>
  <?php include(INCLUDE_PATH . "/layouts/footer.php") ?>
</body>
</html>

Trên trình duyệt của bạn, truy cập http://localhost/user-accounts/admin/roles/roleList.php. Và bây giờ chúng tôi cũng có thể tạo, chỉnh sửa, cập nhật và xóa các vai trò.

Một lần nữa cảm ơn đã theo dõi. Hy vọng rằng tôi sẽ gặp lại bạn trong phần tiếp theo, nơi chúng tôi làm việc về quyền và chỉnh sửa hồ sơ người dùng.


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Mysql bao phủ so với tổng hợp và chỉ số cột

  2. Tôi có đang sử dụng tổng hợp kết nối JDBC không?

  3. Cách xử lý các ngoại lệ PDO

  4. PDO + MySQL và mã hóa UTF-8 bị hỏng

  5. Kiến trúc bảo mật:Hướng dẫn cho MySQL