A2oz

How to Display User Details After Login in PHP Source Code?

Published in PHP 1 min read

After a user successfully logs in, you can display their details using PHP by retrieving their information from a database or session. This information can then be presented in a user-friendly format.

Here's a breakdown of the process:

1. Database Interaction

  • Connect to the Database: Establish a connection to your database using PHP's mysqli_connect() or PDO functions.
  • Retrieve User Data: Use SQL queries to fetch the user's details based on their login credentials (usually their username or email).
  • Store Data: Store the retrieved data in variables for later use.

2. Session Management

  • Start a Session: Begin a session using session_start().
  • Store User Details: Store the retrieved user data in session variables. This allows you to access the information throughout the user's session.

3. Display User Details

  • Retrieve Session Data: Access the user details stored in session variables using $_SESSION.
  • Display Information: Use HTML to present the user details in a visually appealing format.

Example:

<?php
session_start();

// Database connection details
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

// Retrieve user details from the database
$sql = "SELECT * FROM users WHERE username = '" . $_SESSION['username'] . "'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // Fetch user data
  $row = $result->fetch_assoc();

  // Display user details
  echo "<h2>Welcome, " . $row["username"] . "</h2>";
  echo "<p>Your email is: " . $row["email"] . "</p>";
} else {
  echo "User not found.";
}

$conn->close();
?>

This example retrieves the user's details from a database table called "users" and displays their username and email. You can customize this code to display other user information, such as their profile picture, address, or other relevant data.

Practical Insights

  • Security: Always sanitize user input to prevent SQL injection vulnerabilities.
  • Data Privacy: Only display user data that is necessary and relevant.
  • User Experience: Design the user interface to be clear and easy to navigate.

Remember to adapt this code to your specific application requirements and database structure.

Related Articles