Post Date: October 26, 2018
Last Updated: October 01, 2026
Introduction
Editing user profile details is a common feature in web applications. Angular provides tools to build dynamic forms, retrieve user information from a backend, and submit updated data.
In this guide, we will create a profile editing form using Angular, connect it to a PHP backend, and update user information stored in a MySQL database.
Prerequisites
Before getting started, ensure you have:
- Node.js and npm installed.
- Angular CLI installed.
- Basic knowledge of Angular, TypeScript, HTML, and PHP.
- PHP and MySQL configured on your server.
- A database to store user profile information.
Implementation
Step 1: Create an Angular Project
Create a new Angular project using the Angular CLI:
ng new profile-editor
Navigate to the project directory:
cd profile-editor
Generate a component if you want to separate the profile editing functionality:
ng generate component profile
Step 2: Create the Profile Editing Form
Open the component’s HTML file and add the following form:
<h2>Edit Profile</h2> <form (ngSubmit)="updateProfile()"> <label>Name:</label> <input type="text" [(ngModel)]="profile.name" name="name" required> <label>Gender:</label> <input type="text" [(ngModel)]="profile.gender" name="gender"> <label>Email:</label> <input type="email" [(ngModel)]="profile.email" name="email"> <label>Qualification:</label> <input type="text" [(ngModel)]="profile.qualification" name="qualification"> <label>Hobbies:</label> <input type="text" [(ngModel)]="profile.hobbies" name="hobbies"> <label>Phone Number:</label> <input type="text" [(ngModel)]="profile.phone" name="phone"> <button type="submit">Update</button> <button type="button" (click)="logout()">Logout</button> </form>
The [(ngModel)] directive provides two-way data binding, allowing the form fields to display and update values from the component.
Step 3: Configure the Angular Component
Open the component’s TypeScript file and configure the profile data and HTTP requests.
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
interface Profile {
id: number;
name: string;
gender: string;
email: string;
qualification: string;
hobbies: string;
phone: string;
}
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
profile: Profile = {
id: 1,
name: '',
gender: '',
email: '',
qualification: '',
hobbies: '',
phone: ''
};
constructor(private http: HttpClient) {}
ngOnInit(): void {
this.loadProfile();
}
loadProfile(): void {
this.http.get<Profile>('http://localhost/fetch.php?id=1')
.subscribe({
next: (data) => this.profile = data,
error: (error) => console.error('Error fetching profile:', error)
});
}
updateProfile(): void {
this.http.post('http://localhost/update.php', this.profile)
.subscribe({
next: (response) => console.log('Profile updated:', response),
error: (error) => console.error('Update failed:', error)
});
}
logout(): void {
console.log('Logout clicked');
}
}
This component uses HttpClient to retrieve profile information and send updates to the PHP backend. The example uses a fixed profile ID for demonstration. In a real application, use the authenticated user’s identity rather than trusting a client-provided ID.
Step 4: Configure Angular HTTP and Forms
For a standalone Angular application, configure HTTP and forms in the appropriate application setup.
For example, in app.config.ts:
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient()
]
};
Import FormsModule into the component if it is standalone:
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-profile',
standalone: true,
imports: [FormsModule],
templateUrl: './profile.component.html',
styleUrls: ['./profile.component.css']
})
If you are using an NgModule-based application, import FormsModule and HttpClientModule in the relevant module instead. Avoid configuring both approaches unnecessarily.
Step 5: Create the PHP File to Fetch Profile Details
Create a file named fetch.php in your PHP server’s application directory.
The following example retrieves profile details from MySQL using a prepared statement.
<?php
header('Content-Type: application/json');
$conn = new mysqli('localhost', 'root', '', 'profile');
if ($conn->connect_error) {
http_response_code(500);
echo json_encode(['error' => 'Database connection failed']);
exit;
}
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if (!$id) {
http_response_code(400);
echo json_encode(['error' => 'Invalid profile ID']);
exit;
}
$stmt = $conn->prepare(
'SELECT id, name, gender, gmail AS email,
qualification, hobbies, phoneno AS phone
FROM model WHERE id = ?'
);
$stmt->bind_param('i', $id);
$stmt->execute();
$result = $stmt->get_result();
$profile = $result->fetch_assoc();
if ($profile) {
echo json_encode($profile);
} else {
http_response_code(404);
echo json_encode(['error' => 'Profile not found']);
}
$stmt->close();
$conn->close();
This script connects to the database, retrieves the requested profile, and returns the information in JSON format.
Step 6: Create the PHP File to Update Profile Details
Create another file named update.php.
<?php
header('Content-Type: application/json');
$conn = new mysqli('localhost', 'root', '', 'profile');
if ($conn->connect_error) {
http_response_code(500);
echo json_encode(['error' => 'Database connection failed']);
exit;
}
$data = json_decode(file_get_contents('php://input'), true);
if (!is_array($data)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid request data']);
exit;
}
$id = filter_var($data['id'] ?? null, FILTER_VALIDATE_INT);
$name = trim($data['name'] ?? '');
$gender = trim($data['gender'] ?? '');
$email = trim($data['email'] ?? '');
$qualification = trim($data['qualification'] ?? '');
$hobbies = trim($data['hobbies'] ?? '');
$phone = trim($data['phone'] ?? '');
if (!$id || $name === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
http_response_code(400);
echo json_encode(['error' => 'Invalid profile details']);
exit;
}
$stmt = $conn->prepare(
'UPDATE model
SET name = ?, gender = ?, gmail = ?,
qualification = ?, hobbies = ?, phoneno = ?
WHERE id = ?'
);
$stmt->bind_param(
'ssssssi',
$name,
$gender,
$email,
$qualification,
$hobbies,
$phone,
$id
);
if ($stmt->execute()) {
echo json_encode(['message' => 'Profile updated successfully']);
} else {
http_response_code(500);
echo json_encode(['error' => 'Unable to update profile']);
}
$stmt->close();
$conn->close();
Prepared statements help prevent SQL injection. In production, the backend must also verify that the authenticated user is authorized to update the requested profile. Use secure database credentials rather than the example’s local development credentials.
Step 7: Run the Angular Application
Start the Angular development server:
ng serve
Open the application in your browser:
http://localhost:4200
Ensure that the PHP backend is running and configured to accept requests from the Angular development server. If the frontend and backend use different origins, configure CORS appropriately on the backend.
Test the following operations:
- Load existing profile details.
- Edit the form fields.
- Submit updated information.
- Verify the changes in the database.
- Test error handling for invalid or missing data.
Conclusion
Angular makes it easier to create dynamic profile editing forms with two-way data binding and HTTP communication. By integrating Angular with PHP and MySQL, you can retrieve user information, allow users to edit their details, and save updates to the database.
Always implement proper validation, authentication, and authorization when handling profile information in a production application.
FAQs
1. How does Angular retrieve profile details?
Angular uses HttpClient to send a request to the backend. The backend retrieves the profile from the database and returns it as JSON.
2. What is two-way data binding in Angular?
Two-way data binding synchronizes data between the component and the form using directives such as [(ngModel)].
3. Why is HttpClient used?
HttpClient enables Angular applications to communicate with backend services through HTTP requests such as GET and POST.
4. Can Angular update MySQL directly?
No. Angular should communicate with a backend API, such as a PHP application, which handles database operations securely.
Related Articles
Talk to Our Experts
Need help with Angular development or web application integration? Our experts can help you build and maintain reliable web solutions.
Get in touch with us: Contact our team