Php sql admin login

User Management System with PHP & MySQL

In our previous tutorial, we have explained how to develop School Management System with PHP & MySQL. In this tutorial, we will explain how to develop User Management System with PHP & MySQL.

User management is an important part of any web application where users can create their account and manage. The users are allowed to register their account and login to access their account. The users are also managed by administrator to allow certain roles or update users info.

So if you’re looking for solution to build secure user management system then you’re here the right place. In this tutorial, you will learn how to create secure user management system with PHP and MySQL. You would also like to checkout Login and Registration System with PHP & MySQL to implement user login and registration.

We will implement functionality to manage user operations like user registration, user email verification, login, password reset and edit profile. We will also create Admin panel to manage users at admin end to create new user, edit existing users details and delete user.

We will cover this tutorial in easy steps with live example to manage users from front-end and administrator end.

Читайте также:  Python check port is open

So let’s start implementing user management system with PHP and MySQL. Before we begin, take a look on files structure for this example.

User Login and Registration features:

  • User registration with email verification.
  • User Login with remember password.
  • Forget password & reset password.
  • User profile.
  • User profile edit & save.

Admin Panel features:

  • Admin login.
  • Admin password reset.
  • Admin profile.
  • Dashboard with users stats.
  • Users list.
  • Add new user with role.
  • Edit & save user.
  • Delete user.

So let’s start implementing user management system with PHP and MySQL. Before we begin, take a look on files structure for this example.

  • index.php: User dashboard
  • register.php: Handle User registration.
  • verify.php: Complete user registration after email verification.
  • login.php: Handle user login.
  • forget_password.php: Handle user forget password reset.
  • reset_password.php: Reset new password.
  • account.php: User profile.
  • edit_account.php: edit user profile.
  • User.php: Class which hold user methods.

There will be following files for Admin section to manage users.

  • index.php: Handle user login
  • dashboard.php: Display users stats
  • change_password.php: Change admin password.
  • profile.php: Display admin profile.
  • user_list.php: Display user list, add new user, edit and delete user.

Step1: Create MySQL Database Table

First we will create MySQL database table user to store user details to manage users.

CREATE TABLE `user` ( `id` int(11) NOT NULL, `first_name` varchar(50) NOT NULL, `last_name` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `gender` enum('male','female') CHARACTER SET utf8 NOT NULL, `mobile` varchar(50) NOT NULL, `designation` varchar(50) NOT NULL, `image` varchar(250) NOT NULL, `type` varchar(250) NOT NULL DEFAULT 'general', `status` enum('active','pending','deleted','') NOT NULL DEFAULT 'pending', `authtoken` varchar(250) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step2: Implement User Registration

We will design user registration form in register.php file and handle user registration on form submit.

In class User.php, we will create method register() to implement user registration. We will send an email verification email to user’s email address with link to verify and complete registration.

public function register()< $message = ''; if(!empty($_POST["register"]) && $_POST["email"] !='') < $sqlQuery = "SELECT * FROM ".$this->userTable." WHERE email='".$_POST["email"]."'"; $result = mysqli_query($this->dbConnect, $sqlQuery); $isUserExist = mysqli_num_rows($result); if($isUserExist) < $message = "User already exist with this email address."; >else < $authtoken = $this->getAuthtoken($_POST["email"]); $insertQuery = "INSERT INTO ".$this->userTable."(first_name, last_name, email, password, authtoken) VALUES ('".$_POST["firstname"]."', '".$_POST["lastname"]."', '".$_POST["email"]."', '".md5($_POST["passwd"])."', '".$authtoken."')"; $userSaved = mysqli_query($this->dbConnect, $insertQuery); if($userSaved) < $link = "Verify Email"; $toEmail = $_POST["email"]; $subject = "Verify email to complete registration"; $msg = "Hi there, click on this ".$link." to verify email to complete registration."; $msg = wordwrap($msg,70); $headers = "From: info@webdamn.com"; if(mail($toEmail, $subject, $msg, $headers)) < $message = "Verification email send to your email address. Please check email and verify to complete registration."; >> else < $message = "User register request failed."; >> > return $message; >

We will create a method verifyRegister() in class User.php to verify user email to complete registration.

public function verifyRegister()< $verifyStatus = 0; if(!empty($_GET["authtoken"]) && $_GET["authtoken"] != '') < $sqlQuery = "SELECT * FROM ".$this->userTable." WHERE authtoken='".$_GET["authtoken"]."'"; $resultSet = mysqli_query($this->dbConnect, $sqlQuery); $isValid = mysqli_num_rows($resultSet); if($isValid)< $userDetails = mysqli_fetch_assoc($resultSet); $authtoken = $this->getAuthtoken($userDetails['email']); if($authtoken == $_GET["authtoken"]) < $updateQuery = "UPDATE ".$this->userTable." SET status = 'active' WHERE id']."'"; $isUpdated = mysqli_query($this->dbConnect, $updateQuery); if($isUpdated) < $verifyStatus = 1; >> > > return $verifyStatus; >

Step3: Implement User Login

We will design user login form in login.php file and handle login functionality on form submit.

 
Log In
?>
?>" placeholder="email">
?>" placeholder="password">
Don't have an account! Register Here.

We will create a method login() in class User.php to handle user login functionality.

public function login() < $errorMessage = ''; if(!empty($_POST["login"]) && $_POST["loginId"]!=''&& $_POST["loginPass"]!='') < $loginId = $_POST['loginId']; $password = $_POST['loginPass']; if(isset($_COOKIE["loginPass"]) && $_COOKIE["loginPass"] == $password) < $password = $_COOKIE["loginPass"]; >else < $password = md5($password); >$sqlQuery = "SELECT * FROM ".$this->userTable." WHERE email='".$loginId."' AND password='".$password."' AND status = 'active'"; $resultSet = mysqli_query($this->dbConnect, $sqlQuery); $isValidLogin = mysqli_num_rows($resultSet); if($isValidLogin) < if(!empty($_POST["remember"]) && $_POST["remember"] != '') < setcookie ("loginId", $loginId, time()+ (10 * 365 * 24 * 60 * 60)); setcookie ("loginPass", $password, time()+ (10 * 365 * 24 * 60 * 60)); >else < $_COOKIE['loginId' ]=''; $_COOKIE['loginPass'] = ''; >$userDetails = mysqli_fetch_assoc($resultSet); $_SESSION["userid"] = $userDetails['id']; $_SESSION["name"] = $userDetails['first_name']." ".$userDetails['last_name']; header("location: index.php"); > else < $errorMessage = "Invalid login!"; >> else if(!empty($_POST["loginId"])) < $errorMessage = "Enter Both user and password!"; >return $errorMessage; >

We will create object of user class and call user method login() to complete user login.

include('class/User.php'); $user = new User(); $message = $user->login();

Step4: Implement User Password Reset

We will design user password reset form in reset_password.php file to user password. The user email is entered and submitted in forget_password.php and a password reset email will be send to user email address. When user click on password reset link, it will redirect user to reset password form and ask the user to enter new password to save.

 
Reset Password
?>
" />
else < ?>Invalid password reset request. ?>

We will create a method resetPassword() in class User.php to send password reset email to user.

public function resetPassword() < $message = ''; if($_POST['email'] == '') < $message = "Please enter username or email to proceed with password reset"; >else < $sqlQuery = " SELECT email FROM ".$this->userTable." WHERE email='".$_POST['email']."'"; $result = mysqli_query($this->dbConnect, $sqlQuery); $numRows = mysqli_num_rows($result); if($numRows) < $user = mysqli_fetch_assoc($result); $authtoken = $this->getAuthtoken($user['email']); $link="Reset Password"; $toEmail = $user['email']; $subject = "Reset your password on examplesite.com"; $msg = "Hi there, click on this ".$link." to reset your password."; $msg = wordwrap($msg,70); $headers = "From: info@webdamn.com"; if(mail($toEmail, $subject, $msg, $headers)) < $message = "Password reset link send. Please check your mailbox to reset password."; >> else < $message = "No account exist with entered email address."; >> return $message; >

We will create a method savePassword() in class User.php to save new password.

public function savePassword() < $message = ''; if($_POST['password'] != $_POST['cpassword']) < $message = "Password does not match the confirm password."; >else if($_POST['authtoken']) < $sqlQuery = " SELECT email, authtoken FROM ".$this->userTable." WHERE authtoken='".$_POST['authtoken']."'"; $result = mysqli_query($this->dbConnect, $sqlQuery); $numRows = mysqli_num_rows($result); if($numRows) < $userDetails = mysqli_fetch_assoc($result); $authtoken = $this->getAuthtoken($userDetails['email']); if($authtoken == $_POST['authtoken']) < $sqlUpdate = " UPDATE ".$this->userTable." SET password='".md5($_POST['password'])."' WHERE email='".$userDetails['email']."' AND authtoken='".$authtoken."'"; $isUpdated = mysqli_query($this->dbConnect, $sqlUpdate); if($isUpdated) < $message = "Password saved successfully. Please Login to access account."; > > else < $message = "Invalid password change request."; >> else < $message = "Invalid password change request."; >> return $message; >

Step5: Manage User Profile

We will design user profile edit forum in edit_account.php to edit user details and save.

 
Edit Account Details
?>
" >
" >
" required>
" >
" >
;

We will create a method editAccount() in class User.php edit and save user profile.

public function editAccount () < $message = ''; $updatePassword = ''; if(!empty($_POST["passwd"]) && $_POST["passwd"] != '' && $_POST["passwd"] != $_POST["cpasswd"]) < $message = "Confirm passwords do not match."; >else if(!empty($_POST["passwd"]) && $_POST["passwd"] != '' && $_POST["passwd"] == $_POST["cpasswd"]) < $updatePassword = ", password='".md5($_POST["passwd"])."' "; >$updateQuery = "UPDATE ".$this->userTable." SET first_name = '".$_POST["firstname"]."', last_name = '".$_POST["lastname"]."', email = '".$_POST["email"]."', mobile = '".$_POST["mobile"]."' , designation = '".$_POST["designation"]."', gender = '".$_POST["gender"]."' $updatePassword WHERE "; $isUpdated = mysqli_query($this->dbConnect, $updateQuery); if($isUpdated) < $_SESSION["name"] = $_POST['firstname']." ".$_POST['lastname']; $message = "Account details saved."; >return $message; >

Step6: Implement Admin Login

We will design form in index.php to handle admin login.

 
Admin In
?>
User: admin@webdamn.com
password:123

We will create method adminLogin() in class User.php to complete admin login.

public function adminLogin()< $errorMessage = ''; if(!empty($_POST["login"]) && $_POST["email"]!=''&& $_POST["password"]!='') < $email = $_POST['email']; $password = $_POST['password']; $sqlQuery = "SELECT * FROM ".$this->userTable." WHERE email='".$email."' AND password='".md5($password)."' AND status = 'active' AND type = 'administrator'"; $resultSet = mysqli_query($this->dbConnect, $sqlQuery); $isValidLogin = mysqli_num_rows($resultSet); if($isValidLogin) < $userDetails = mysqli_fetch_assoc($resultSet); $_SESSION["adminUserid"] = $userDetails['id']; $_SESSION["admin"] = $userDetails['first_name']." ".$userDetails['last_name']; header("location: dashboard.php"); >else < $errorMessage = "Invalid login!"; >> else if(!empty($_POST["login"])) < $errorMessage = "Enter Both user and password!"; >return $errorMessage; >

Step7: Admin Dishboard

We will design HTML in dashboard.php to display users stats in admin dashboard.

 
My Dashboard
totalUsers(""); ?>
Total Users
totalUsers('active'); ?>
Total Active Users
totalUsers('pending'); ?>
Total Pending Users
totalUsers('deleted'); ?>
Total Deleted Users

Step8: Manage User in Admin Panel

We will design HTML in user_list.php to display users list in Datatable. We will design modal to add and edit user. Als handle muser delete functionality.

 
User List
ID Name Gender Email Mobile Role

Edit User

;
;
;

We will create JavaScript file users.js to handle Datatable data load, handle add, edit and delete records.

$(document).ready(function()< var usersData = $('#userList').DataTable(< "lengthChange": false, "processing":true, "serverSide":true, "order":[], "ajax":< url:"action.php", type:"POST", data:, dataType:"json" >, "columnDefs":[ < "targets":[0, 7, 8], "orderable":false, >, ], "pageLength": 10 >); $(document).on('click', '.delete', function()< var userid = $(this).attr("id"); var action = "userDelete"; if(confirm("Are you sure you want to delete this user?")) < $.ajax(< url:"action.php", method:"POST", data:, success:function(data) < usersData.ajax.reload(); >>) > else < return false; >>); $('#addUser').click(function() Add User"); $('#action').val('addUser'); $('#save').val('Add User'); >); $(document).on('click', '.update', function()< var userid = $(this).attr("id"); var action = 'getUser'; $.ajax(< url:'action.php', method:"POST", data:, dataType:"json", success:function(data) < $('#userModal').modal('show'); $('#userid').val(data.id); $('#firstname').val(data.first_name); $('#lastname').val(data.last_name); $('#email').val(data.email); $('#password').val(data.password); $('#passwordSection').hide(); if(data.gender == 'male') < $('#male').prop("checked", true); >else if(data.gender == 'female') < $('#female').prop("checked", true); >if(data.status == 'active') < $('#active').prop("checked", true); >else if(data.gender == 'pending') < $('#pending').prop("checked", true); >if(data.type == 'general') < $('#general').prop("checked", true); >else if(data.type == 'administrator') < $('#administrator').prop("checked", true); >$('#mobile').val(data.mobile); $('#designation').val(data.designation); $('.modal-title').html(" Edit User"); $('#action').val('updateUser'); $('#save').val('Save'); > >) >); $(document).on('submit','#userForm', function(event) < event.preventDefault(); $('#save').attr('disabled','disabled'); var formData = $(this).serialize(); $.ajax(< url:"action.php", method:"POST", data:formData, success:function(data)< $('#userForm')[0].reset(); $('#userModal').modal('hide'); $('#save').attr('disabled', false); usersData.ajax.reload(); >>) >); >);

We will create method getUserList() in class User.php to get user list and return as JSON data to display in Datatables.

public function getUserList()< $sqlQuery = "SELECT * FROM ".$this->userTable." WHERE id !='".$_SESSION['adminUserid']."' "; if(!empty($_POST["search"]["value"])) < $sqlQuery .= '(id LIKE "%'.$_POST["search"]["value"].'%" '; $sqlQuery .= ' OR first_name LIKE "%'.$_POST["search"]["value"].'%" '; $sqlQuery .= ' OR last_name LIKE "%'.$_POST["search"]["value"].'%" '; $sqlQuery .= ' OR designation LIKE "%'.$_POST["search"]["value"].'%" '; $sqlQuery .= ' OR status LIKE "%'.$_POST["search"]["value"].'%" '; $sqlQuery .= ' OR mobile LIKE "%'.$_POST["search"]["value"].'%") '; >if(!empty($_POST["order"])) < $sqlQuery .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' '; >else < $sqlQuery .= 'ORDER BY id DESC '; >if($_POST["length"] != -1) < $sqlQuery .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length']; >$result = mysqli_query($this->dbConnect, $sqlQuery); $sqlQuery1 = "SELECT * FROM ".$this->userTable." WHERE id !='".$_SESSION['adminUserid']."' "; $result1 = mysqli_query($this->dbConnect, $sqlQuery1); $numRows = mysqli_num_rows($result1); $userData = array(); while( $users = mysqli_fetch_assoc($result) ) < $userRows = array(); $status = ''; if($users['status'] == 'active') < $status = 'Active'; > else if($users['status'] == 'pending') < $status = 'Inactive'; > else if($users['status'] == 'deleted') < $status = 'Deleted'; > $userRows[] = $users['id']; $userRows[] = ucfirst($users['first_name']." ".$users['last_name']); $userRows[] = $users['gender']; $userRows[] = $users['email']; $userRows[] = $users['mobile']; $userRows[] = $users['type']; $userRows[] = $status; $userRows[] = ''; $userRows[] = ''; $userData[] = $userRows; > $output = array( "draw" => intval($_POST["draw"]), "recordsTotal" => $numRows, "recordsFiltered" => $numRows, "data" => $userData ); echo json_encode($output); >

You may also like:

  • Build Helpdesk System with jQuery, PHP & MySQL
  • Build Online Voting System with PHP & MySQL
  • School Management System with PHP & MySQL
  • DataTables Add Edit Delete with CodeIgniter
  • Create RESTful API using CodeIgniter
  • Build Reusable Captcha Script with PHP
  • Product Search Filtering using Ajax, PHP & MySQL
  • Image Upload and Crop in Modal with jQuery, PHP & MySQL
  • Build Push Notification System with PHP & MySQL
  • Project Management System with PHP and MySQL
  • Hospital Management System with PHP & MySQL
  • Build Newsletter System with PHP and MySQL
  • Skeleton Screen Loading Effect with Ajax and PHP
  • Build Discussion Forum with PHP and MySQL
  • Customer Relationship Management (CRM) System with PHP & MySQL
  • Online Exam System with PHP & MySQL
  • Expense Management System with PHP & MySQL

You can view the live demo from the Demo link and can download the script from the Download link below.
Admin Demo User Demo Download

156 thoughts on “ User Management System with PHP & MySQL ”

I have fixed the config issue but when i try to register a new user i get the response of
User register request failed’. Anybody have any ideas please I have checked the sql connection that is fine.

Источник

Оцените статью