User profile edit in PHP and MYSQL | Update user account details after logging in using PHP


The update operation is very important for dynamic web development.  We are creating login and registration from scratch. In this tutorial, we will learn how to update user profile after logging in to user account using PHP and MYSQL database. A login system requires many features to give a better environment for the account dashboard. On my account page or dashboard, users can change their profile details after login, like – user can change the first name, last name, username, profile image, etc. We had discussed update operation in previous PHP tutorials. We will use an update operation with user session-id or email. 
Let’s discuss the process – 

How do users edit their profile after logging into account in PHP? 

The update operation plays an important role. We will use an update operation with session user email. It will help to update user data by authorized (who can log in to account) users.  
For example- A user enters login and password to log in own account. The user gets logged in and redirects to my account page. My account page contains user details like – user first name, user last name, and user username. On my account user can see the edit profile button and when the user clicks on the edit profile button, he redirects to the update page where the user can change the first name, last name, username, user profile image, etc. 
The update operation executes and data update through the current session email id. We can set the user id while login. 
We already created an account page with an edit profile button. You can check here(Login and registration in PHP – Part 1 )
In these tutorials, we are using PHP and bootstrap.
Bootstrap Bootstrap is an open-source HTML and CSS framework which allows the design of websites to use ready-made classes and modules. We will create a user edit profile form using bootstrap also. 
edit-profile.php

<?php require_once("config.php");
if(!isset($_SESSION["login_sess"])) 
{
    header("location:login.php"); 
}
  $email=$_SESSION["login_email"];
  $findresult = mysqli_query($dbc, "SELECT * FROM users WHERE email= '$email'");
if($res = mysqli_fetch_array($findresult))
{
$username = $res['username']; 
$oldusername =$res['username']; 
$fname = $res['fname'];   
$lname = $res['lname'];  
$email = $res['email'];  
$image= $res['image'];
}
 ?> 
 <!DOCTYPE html>
<html>
<head>
    <title>Edit Profile</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css"> 
    <link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-sm-3">
        </div>
        <div class="col-sm-6">
           
     <form action="" method="POST" enctype='multipart/form-data'>
  <div class="login_form">

 <img src="https://technosmarter.com/assets/images/logo.png" alt="Techno Smarter" class="logo img-fluid"> <br> <?php 
 if(isset($_POST['update_profile'])){
$fname=$_POST['fname'];
 $lname=$_POST['lname'];  
 $username=$_POST['username']; 
 $folder='images/';
 $file = $_FILES['image']['tmp_name'];  
$file_name = $_FILES['image']['name']; 
$file_name_array = explode(".", $file_name); 
 $extension = end($file_name_array);
 $new_image_name ='profile_'.rand() . '.' . $extension;
  if ($_FILES["image"]["size"] >1000000) {
   $error[] = 'Sorry, your image is too large. Upload less than 1 MB in size .';
 
}
 if($file != "")
  {
if($extension!= "jpg" && $extension!= "png" && $extension!= "jpeg"
&& $extension!= "gif" && $extension!= "PNG" && $extension!= "JPG" && $extension!= "GIF" && $extension!= "JPEG") {
    
   $error[] = 'Sorry, only JPG, JPEG, PNG & GIF files are allowed';   
}
}

$sql="SELECT * from users where username='$username'";
      $res=mysqli_query($dbc,$sql);
   if (mysqli_num_rows($res) > 0) {
$row = mysqli_fetch_assoc($res);

   if($oldusername!=$username){
     if($username==$row['username'])
     {
           $error[] ='Username alredy Exists. Create Unique username';
          } 
   }
}
    if(!isset($error)){ 
          if($file!= "")
          {
            $stmt = mysqli_query($dbc,"SELECT image FROM  users WHERE email='$email'");
            $row = mysqli_fetch_array($stmt); 
            $deleteimage=$row['image'];
unlink($folder.$deleteimage);
move_uploaded_file($file, $folder . $new_image_name); 
mysqli_query($dbc,"UPDATE users SET image='$new_image_name' WHERE email='$email'");
          }
           $result = mysqli_query($dbc,"UPDATE users SET fname='$fname',lname='$lname',username='$username' WHERE email='$email'");
           if($result)
           {
       header("location:account.php?profile_updated=1");
           }
           else 
           {
            $error[]='Something went wrong';
           }

    }


        }    
        if(isset($error)){ 

foreach($error as $error){ 
  echo '<p class="errmsg">'.$error.'</p>'; 
}
}


        ?> 
     <form method="post" enctype='multipart/form-data' action="">
          <div class="row">
            <div class="col"></div>
           <div class="col-6"> 
            <center>
            <?php if($image==NULL)
                {
                 echo '<img src="https://technosmarter.com/assets/icon/user.png">';
                } else { echo '<img src="images/'.$image.'" style="height:80px;width:auto;border-radius:50%;">';}?> 
                <div class="form-group">
                <label>Change Image &#8595;</label>
                <input class="form-control" type="file" name="image" style="width:100%;" >
            </div>

  </center>
           </div>
            <div class="col"><p><a href="logout.php"><span style="color:red;">Logout</span> </a></p>
         </div>
          </div>

          <div class="form-group">
          <div class="row"> 
            <div class="col-3">
                <label>First Name</label>
            </div>
             <div class="col">
                <input type="text" name="fname" value="<?php echo $fname;?>" class="form-control">
            </div>
          </div>
      </div>
      <div class="form-group">
 <div class="row"> 
            <div class="col-3">
                <label>Last Name</label>
            </div>
             <div class="col">
                <input type="text" name="lname" value="<?php echo $lname;?>" class="form-control">
            </div>
          </div>
      </div>
      <div class="form-group">
 <div class="row"> 
            <div class="col-3">
                <label>Username</label>
            </div>
             <div class="col">
                <input type="text" name="username" value="<?php echo $username;?>" class="form-control">
            </div>
          </div>
      </div>
           <div class="row">
            <div class="col-sm-6">
            </div>
            <div class="col-sm-6">
<button  class="btn btn-success" name="update_profile">Save Profile</button>
            </div>
           </div>
       </form>
        </div>
        <div class="col-sm-3">
        </div>
    </div>
</div> 
</body>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"></script>
</html>


Note:-  Kindly create a folder with name = images in the same path then execute the code above. 
In the PHP file above  – 
1.    First of all, we fetch current user data using session email like we already fetched data on the account.php page. It’s very easy to fetch user row by session email from the MYSQL database using PHP. 
2.    In the update operation, we always create and form and fetch user-related data from the database and echo it in the text box. We are updating the image also using type files. It will help to update user profile images during the session. 
3.    In this profile update operation, we validated the username if already exists
4.    When the user clicks the save button the data hold by the POST method and updated by the update query using session email. 
5.    When we write user profile update code during the session, we create a condition for image upload or not change old uploaded image. 
Like – if the user does not browse any image, it means image_temp will be empty and we never update the null value in the database. That’s why we create if condition for this situation- 
When the image doesn’t browse then do not update and upload an image and when the image browses then delete an old image, move the new user profile image into the folder (images) and also update the new image into the database using session-id or email. You can use a user id or email. 
 


Please Share

Recommended Posts:-