Edit Profile

How to edit a user profile on the front end?

You can do that by copy your theme’s page.php to a new file named something like user-profile.php and add to the very top of it this code:

 $current_user->ID, 'user_pass' => esc_attr( $_POST['pass1'] ) ) ); else $error[] = __('The passwords you entered do not match. Your password was not updated.', 'profile'); > /* Update user information. */ if ( !empty( $_POST['url'] ) ) wp_update_user( array( 'ID' => $current_user->ID, 'user_url' => esc_url( $_POST['url'] ) ) ); if ( !empty( $_POST['email'] ) )< if (!is_email(esc_attr( $_POST['email'] ))) $error[] = __('The Email you entered is not valid. please try again.', 'profile'); elseif(email_exists(esc_attr( $_POST['email'] )) != $current_user->ID ) $error[] = __('This email is already used by another user. try a different one.', 'profile'); else < wp_update_user( array ('ID' =>$current_user->ID, 'user_email' => esc_attr( $_POST['email'] ))); > > if ( !empty( $_POST['first-name'] ) ) update_user_meta( $current_user->ID, 'first_name', esc_attr( $_POST['first-name'] ) ); if ( !empty( $_POST['last-name'] ) ) update_user_meta($current_user->ID, 'last_name', esc_attr( $_POST['last-name'] ) ); if ( !empty( $_POST['description'] ) ) update_user_meta( $current_user->ID, 'description', esc_attr( $_POST['description'] ) ); /* Redirect so the page will show updated info.*/ /*I am not Author of this Code- I don't know why but it worked for me after changing below line to if ( count($error) == 0 )< */ if ( count($error) == 0 ) < //action hook for plugins and extra fields saving do_action('edit_user_profile_update', $current_user->ID); wp_redirect( get_permalink() ); exit; > > ?> 

then replace the loop of that page with this one:

Читайте также:  Лямбда функции python try

«> 0 ) echo ‘

«, $error) . ‘

‘; ?> «>

ID ); ?>»/>

ID ); ?>»/>

ID ); ?>»/>

ID ); ?>»/>

and all that is left for you to do is create a new page and select the «user profile» as the page template.

now if all of this is too much you can use some plugins that do the hard work for you like:

Источник

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

 $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']; >?>   

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 '

'.$error.'

'; > > ?>
'; > else < echo '';>?>

Logout

" >
" >
" >

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.

Источник

Редактирование профиля пользователя php

Задача редактирование профиля(страна, адрес, телефон, индекс, и тд ) пользователя самим пользователем на сайте.
Редактировать пользователь может желаемый из параметров введя новый и нажав кнопку ОК. Те поля которые пользователь не заполнил считать, что их не нужно редактировать.

сделал, что пользователь может отредактировать один параметр.

if (isset($_POST['adress'])) < $adress = $_POST['adress']; >$result = mysql_query("UPDATE users SET adress='$adress' WHERE login='$old_login'",$db);//обновляем adress if ($result=='TRUE') 
if (isset($_POST['adress'])) if (isset($_POST['siti'])) $result = mysql_query("UPDATE users SET adress='$adress',siti='$siti' WHERE login='$old_login'",$db); if ($result=='TRUE') 

и еще,
если поля оставить пусты и нажать кнопку ОК, то код считает что пользователь хочет поменять данные на пустоту и они стирается в базе.

Выводишь все данные пользователя в форму.
После отправки формы, изменяешь все параметры на новые, которые указал пользователь и все.

Выводишь все данные пользователя в форму.
После отправки формы, изменяешь все параметры на новые, которые указал пользователь и все.

Либо я туплю либо что то еще

if (isset($_POST['adress'])) < $adress = $_POST['adress']; >///пользователь ввел новый адрес $result = mysql_query("UPDATE users SET adress='$adress' WHERE login='$login'",$db);//сохраняям адрес if ($result=='TRUE') 

но параметров несколько и если я для остальных прописываю такой же код, то он не работает

if (isset($_POST['adress'])) //пользователь ввел новый адрес if (isset($_POST['siti'])) //пользователь ввел новый город $result = mysql_query("UPDATE users SET adress='$adress',siti='$siti' WHERE login='$login'",$db);//сохраняем в базу if ($result=='TRUE') 

вроде должно работать по логике - если поле ввода ГОРОД пустое, то присваиваем значение переменной $sity значение sity из базы

так, если пользователь вводит параметры все сделал, но если оставляет поле пустым, как сделать что бы данные не удалялись с базы ??

$_POST = array_map ( 'trim' , $_POST );
/*
$sity = !empty($_POST['sity']) ? $_POST['sity'] : '';
$adress = !empty($_POST['adress']) ? $_POST['adress'] : '';
*/
extract ( $_POST );

if (!empty( $sity ))
mysql ( "UPDATE users SET siti=' $sity ' WHERE login=' $login '" );

if (!empty( $adress ))
mysql ( "UPDATE users SET adress=' $adress ' WHERE login=' $login '" );
.

а еще лучше .. .при редактировании профиля выводить ВСЕ текущие значения в соответствующие им поля, а потом сохранять ВСЕ переданные поля - и не будет проблем. То есть если в БД уже была запись adres="moscow" в форме
и при сохранении все останется
именно это и подразумевает редактирование .
иначе у вас не редактирование профиля получается - а ерунда какая то. типа ввода значений вслепую. типа - не знаю был ли там город и какой - введу ка чего нибудь.

Источник

Simple User Profile With Update Profile Info Using PHP/MYSQL

Good day everyone! Today is another tutorial for all PHP developers, especially for the beginners in PHP programming. I will teach you to create a Simple User Profile With Update Profile Info Using PHP/MYSQL.

This article can answer the question posted in StackOverflow about how to view user’s profiles using PHP.

But before that, make sure you are done creating a simple login and registration. If you are not yet, this tutorial might help you. >> click here

Steps to Create User Profile With Update Profile Info Using PHP/MYSQL

Step 1. First, create a database, name it as any name you desire. In my case, I use “ITSOURCECODE” as the name of the database.

CREATE TABLE `users` ( `user_id` int(11) NOT NULL, `username` text NOT NULL, `password` text NOT NULL, `full_name` text NOT NULL, `gender` text NOT NULL, `age` int(11) NOT NULL, `address` text NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=latin1;

Make sure you are done doing in the login and registration. A link will be seen and view on the link above. And Make sure to Create a “connection.php” file to hold the database connection to our PHP project.

Step 3. For the user’s profile, create and update “profile.php” file then put the following codes.

      

User Profile

Please Fill-out All Fields
Fullname " required />
Gender " />
Age ">
Address ">


Log out
?>

Step 4. Update the “index.php” file by putting the following codes.

    

User Log In

Please Fill-out All Fields
Username
Password


register
0) < ?> > ?>

Step 5. For registration of user profile information, create “register.php” file then put the following codes.

      

Register

Please Fill-out All Fields
Fullname
Gender
Age
Address
Username
Password


LogIn
?>

Step 6. For the logout of user action, create “logout.php” file then put the following codes.

After all the code has been added, you may now test the code by running it to using your desire browser.

For More PHP Projects with Source Code, please visit the link here.

Sample Screenshots:

Profile Info Using PHP/MYSQL user login

Profile Info Using PHP/MYSQL user Profile

Downloadable Source Code

Download the Full Source Code here. userprofile

Inquiries

If you have questions regarding “Simple User Profile With Update Profile Info Using PHP/MYSQL” feel free to ask by commenting below or visit on our contact page. Thank you.

12 thoughts on “Simple User Profile With Update Profile Info Using PHP/MYSQL”

I do not know how to copy this code because the code has been compromised .
Can it be sent to me by email?

Please can I get the source code via email?

Источник

Add, Edit, Delete Record With User Profile in PHP/MySQL

In this tutorial we will create a simpleAdd, Edit, Delete, With User Profile In PHP/MySQL - PDO. The application works if the admin will create or add a new member in the list. Every member that the admin created is compose of their username, description and the profile image. And only the admin can access and delete some users in the system. The purpose of this system is to make the users work easily by identifying every persons profile. The application is programmed using Bootstrap Framework, PHP, and PDO.

Sample Code

    PHP/MySQL Add, Edit, Delete, With User Profile.

      Add Member

    $stmt=$DB_con->prepare('SELECT userid, username, description, userprofile FROM users ORDER BY userid DESC');
    $stmt->execute();
    if($stmt->rowCount()>0)
    while($row=$stmt->fetch(PDO::FETCH_ASSOC))
    extract($row);
    ?>

    echo$username."
    "
    .$description;?>

    echo$row['userid'];?>"> Edit
    echo$row['userid'];?>" title="click for delete" onclick="return confirm('Are You Sure You Want To Delete This User?')"> Delete
    >
    >
    else
    ?>
      No Data Found.
    >
    ?>

result

Hope that you learn in this tutorial. And for more updates and programming tutorials don't hesitate to ask and we will answer your questions and suggestions. Don't forget to LIKE & SHARE this website.

Tags

Источник

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