Create PHP MVC app. Update and delete user data

Home » Tutorials » PHP+MySQL » Create PHP MVC app. Update and delete user data
In last lesson we learnt read data to custom directive. Today we will make update and delete user data feature in our application
Код урока (users.js)
var users = angular.module('users', []);

users.controller("usersController", function($scope, $http){


	$scope.getUserData = function(userId) {
		$http({
			method: "POST",
			url: "http://cabinet.kamil-abzalov.ru/cabinet/users/getUserById",
			data: $.param({id: userId}),
			headers: {'Content-Type': 'application/x-www-form-urlencoded'}
		}).then(function(result){
			$scope.userId = result.data.id;
			$scope.fullName = result.data.fullName;
			$scope.login = result.data.login;
			$scope.email = result.data.email;
			$scope.getRoles();
		})
	}

	$scope.getRoles = function() {
		$http({
			method: "POST",
			url: "http://cabinet.kamil-abzalov.ru/cabinet/users/getUsersRoles",
			headers: {'Content-Type': 'application/x-www-form-urlencoded'}
		}).then(function(result){
			$scope.roles = [];
			for(var i=0; i<result.data.length; i++) {
				$scope.roles.push(result.data[i]);
			}
		})	
	}	
	
	$scope.updateUserData = function() {
		console.log($scope.email);
		$http({
			method: "POST",
			url: "http://cabinet.kamil-abzalov.ru/cabinet/users/updateUserData",
			headers: {'Content-Type': 'application/x-www-form-urlencoded'},
			data: $.param({id: $scope.userId, fullName: $scope.fullName, login: $scope.login, role: $scope.role, email: $scope.email})
		}).then(function(result){
			console.log(result);
		})
	}

	$scope.deleteUser = function(userId) {
		$http({
			method: "POST",
			url: "http://cabinet.kamil-abzalov.ru/cabinet/users/deleteUser",
			headers: {'Content-Type': 'application/x-www-form-urlencoded'},
			data: $.param({id: userId})
		}).then(function(result){
			console.log(result);
		})
	}


});

users.directive('editUser', function(){
	return {
		templateUrl: "/views/edit-user-tpl.php",
		restrict: "E",
		replace: true,
		transclude: true,
		controller: "usersController",
		link: function(scope, element, attrs) {
			scope.showEditForm = function() {
				scope.isShowEditForm = true;
			}
		}
	}
})
Код урока (UsersController)
<?php


class UsersController extends Controller {

	private $pageTpl = "/views/users.tpl.php";


	public function __construct() {
		$this->model = new UsersModel();
		$this->view = new View();
	}

	public function index() {

		if(!$_SESSION['user']) {
			header("Location: /");
		}
		$this->pageData['title'] = "Пользователи";
		$this->pageData['usersList'] = $this->model->getUsers();
		$this->view->render($this->pageTpl, $this->pageData);
	}

	public function getUserById() {

		if(!$_SESSION['user']) {
			header("Location: /");
		}

		if(isset($_POST['id']) && $_POST['id'] != '') {
			$userId = $_POST['id'];
			$userInfo = json_encode($this->model->getUserById($userId));
			echo $userInfo;
		} else {
			echo json_encode(array("success" => false, "text" => "ошибка"));
		}
	}

	public function getUsersRoles() {

		if(!$_SESSION['user']) {
			header("Location: /");
		}

		$roles = $this->model->getRoles();
		if(empty($roles)) {
			echo json_encode(array("success" => false, "text" => "ошибка"));
		} else {
			echo json_encode($roles);
		}

	}

	public function updateUserData() {
		if(!$_SESSION['user']) {
			header("Location: /");
		}

		if(!empty($_POST) && !empty($_POST['id']) && !empty($_POST['fullName']) && !empty($_POST['login']) && !empty($_POST['email']) && !empty($_POST['role'])) {
			$userId = $_POST['id'];
			$userFullName = $_POST['fullName'];
			$userLogin = $_POST['login'];
			$userEmail = $_POST['email'];
			$userRole = $_POST['role'];

			if($this->model->updateUserData($userId, $userFullName, $userLogin, $userEmail, $userRole)) {
				echo json_encode(array("success" => true, "text" => "Данные пользователя обновлены"));	
			} else{
				echo json_encode(array("success" => false, "text" => "Ошибка сохранения"));
			}

		} else {
			echo json_encode(array("success" => false, "text" => "Заполните все поля"));
		}		
	}

	public function deleteUser() {
		if(!$_SESSION['user']) {
			header("Location: /");
		}

		if(!empty($_POST) && !empty($_POST['id'])) {
			$userId = $_POST['id'];

			if($this->model->deleteUser($userId)) {
				echo json_encode(array("success" => true, "text" => "Пользователь удален"));	
			} else{
				echo json_encode(array("success" => false, "text" => "Ошибка удаления"));
			}

		} else {
			echo json_encode(array("success" => false, "text" => "Произошла ошибка при удалении"));
		}		
	}


}
Код урока (UsersModel)
<?php

class UsersModel extends Model {


	public function getUsers() {

		$sql = "SELECT users.id, users.login, users.fullName, users.email, role.name as role FROM users 
				INNER JOIN role ON users.role_id = role.id";

		$stmt = $this->db->prepare($sql);
		$stmt->execute();
		$result = array();
		while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
			$result[$row['id']] = $row;
		}

		return $result;		

	}


	public function getUserById($id) {
		$sql = "SELECT users.id, users.email, users.fullName, users.login, role.name as role FROM users	
				INNER JOIN role ON users.role_id = role.id
				WHERE users.id = :id";


		$stmt = $this->db->prepare($sql);
		$stmt->bindValue(":id", $id, PDO::PARAM_INT);
		$stmt->execute();
		$result = $stmt->fetch(PDO::FETCH_ASSOC);
		if(!empty($result)) {
			return $result;
		} else {
			return false;
		}		
	}

	public function getRoles() {
		$result = array();
		$sql = "SELECT * FROM role";
		$stmt = $this->db->prepare($sql);
		$stmt->execute();
		while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
			$result[] = $row;
		}
		return $result;
	}

	public function updateUserData($userId, $userFullName, $userLogin, $userEmail, $userRole) {
		$sql = "UPDATE users
				SET login =:login, fullName = :fullName, email = :email, role_id = :roleId
				WHERE id =:id
				";
		$stmt = $this->db->prepare($sql);
		$stmt->bindValue(":login", $userLogin, PDO::PARAM_STR);
		$stmt->bindValue(":fullName", $userFullName, PDO::PARAM_STR);
		$stmt->bindValue(":email", $userEmail, PDO::PARAM_STR);
		$stmt->bindValue(":roleId", $userRole, PDO::PARAM_INT);	
		$stmt->bindValue(":id", $userId, PDO::PARAM_INT);
		$stmt->execute();
		return true;	
	}

	public function deleteUser($id) {
		$sql = "DELETE FROM users WHERE id =:id";
		$stmt = $this->db->prepare($sql);
		$stmt->bindValue(":id", $id, PDO::PARAM_INT);
		$stmt->execute();
		return true;	
	}


}

0 Comments

Submit a Comment

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

Подписаться на рассылку

Будьте в курсе - получайте последние статьи на свой email

Ваша подписка успешно оформлена

Pin It on Pinterest

Share This