Display only the current user's details using PHP and MySQL

Display only the current user's details using PHP and MySQL

To display only the current user's details using PHP and MySQL, you'll typically need to perform the following steps:

  1. User Authentication: Ensure that the user is logged in. This often involves using a login system, session management, and storing user information securely.

  2. Database Connection: Establish a connection to your MySQL database.

  3. Query Database: Retrieve the details of the currently logged-in user from the database based on their user ID or any other unique identifier.

  4. Display User Details: Display the user details on the web page.

Here's a simplified example:

Assuming you have a MySQL database with a users table:

CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(255),
    email VARCHAR(255),
    password VARCHAR(255)
);

And a PHP script:

<?php
// Step 1: Check if the user is logged in (you may have a different authentication system)
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php"); // Redirect to login page if not logged in
    exit();
}

// Step 2: Connect to the MySQL database
$host = 'your_host';
$dbname = 'your_database';
$username = 'your_username';
$password = 'your_password';

try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Step 3: Query the database to get user details
$user_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $user_id);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Step 4: Display user details
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Details</title>
</head>
<body>

<h2>User Details</h2>
<p>Username: <?php echo $user['username']; ?></p>
<p>Email: <?php echo $user['email']; ?></p>

</body>
</html>

Note: This is a basic example, and you should adapt it to fit your specific requirements and security considerations. Always use secure practices like parameterized queries to prevent SQL injection.

Examples

  1. PHP MySQL Display Current User Details:

    • Description: How to fetch and display details of the currently logged-in user from a MySQL database using PHP.
    • Code:
      <?php
      session_start();
      $userId = $_SESSION['user_id']; // Assuming user_id is stored in a session variable
      
      // Connect to the database and retrieve user details
      $connection = mysqli_connect('localhost', 'username', 'password', 'database');
      $query = "SELECT * FROM users WHERE id = $userId";
      $result = mysqli_query($connection, $query);
      $userDetails = mysqli_fetch_assoc($result);
      ?>
      
      <h1>Welcome, <?php echo $userDetails['username']; ?></h1>
      <p>Email: <?php echo $userDetails['email']; ?></p>
      <!-- Display other user details as needed -->
      
  2. PHP MySQL Display Current User Details with Prepared Statements:

    • Description: Display current user details using prepared statements for improved security.
    • Code:
      <?php
      session_start();
      $userId = $_SESSION['user_id'];
      
      // Connect to the database and retrieve user details using prepared statement
      $connection = new mysqli('localhost', 'username', 'password', 'database');
      $query = "SELECT * FROM users WHERE id = ?";
      $statement = $connection->prepare($query);
      $statement->bind_param('i', $userId);
      $statement->execute();
      $result = $statement->get_result();
      $userDetails = $result->fetch_assoc();
      $statement->close();
      $connection->close();
      ?>
      
      <h1>Welcome, <?php echo $userDetails['username']; ?></h1>
      <p>Email: <?php echo $userDetails['email']; ?></p>
      <!-- Display other user details as needed -->
      
  3. PHP MySQL Display User Details with Session Authentication:

    • Description: Display user details securely using session-based authentication.
    • Code:
      <?php
      session_start();
      if (!isset($_SESSION['user_id'])) {
          header('Location: login.php'); // Redirect to login page if not logged in
          exit();
      }
      
      $userId = $_SESSION['user_id'];
      
      // Connect to the database and retrieve user details
      $connection = mysqli_connect('localhost', 'username', 'password', 'database');
      $query = "SELECT * FROM users WHERE id = $userId";
      $result = mysqli_query($connection, $query);
      $userDetails = mysqli_fetch_assoc($result);
      ?>
      
      <h1>Welcome, <?php echo $userDetails['username']; ?></h1>
      <p>Email: <?php echo $userDetails['email']; ?></p>
      <!-- Display other user details as needed -->
      
  4. PHP MySQL Display User Details with Error Handling:

    • Description: Implement error handling when fetching and displaying user details.
    • Code:
      <?php
      session_start();
      $userId = $_SESSION['user_id'];
      
      // Connect to the database and retrieve user details with error handling
      $connection = mysqli_connect('localhost', 'username', 'password', 'database');
      if (!$connection) {
          die("Connection failed: " . mysqli_connect_error());
      }
      
      $query = "SELECT * FROM users WHERE id = $userId";
      $result = mysqli_query($connection, $query);
      
      if (!$result) {
          die("Query failed: " . mysqli_error($connection));
      }
      
      $userDetails = mysqli_fetch_assoc($result);
      ?>
      
      <h1>Welcome, <?php echo $userDetails['username']; ?></h1>
      <p>Email: <?php echo $userDetails['email']; ?></p>
      <!-- Display other user details as needed -->
      
  5. PHP MySQL Display User Details with HTML Escaping:

    • Description: Securely display user details by escaping HTML entities to prevent XSS attacks.
    • Code:
      <?php
      session_start();
      $userId = $_SESSION['user_id'];
      
      // Connect to the database and retrieve user details with HTML escaping
      $connection = mysqli_connect('localhost', 'username', 'password', 'database');
      $query = "SELECT * FROM users WHERE id = $userId";
      $result = mysqli_query($connection, $query);
      $userDetails = mysqli_fetch_assoc($result);
      ?>
      
      <h1>Welcome, <?php echo htmlspecialchars($userDetails['username'], ENT_QUOTES, 'UTF-8'); ?></h1>
      <p>Email: <?php echo htmlspecialchars($userDetails['email'], ENT_QUOTES, 'UTF-8'); ?></p>
      <!-- Display other user details as needed -->
      
  6. PHP MySQL Display User Details in a Profile Page:

    • Description: Create a user profile page to display and edit user details.
    • Code:
      <?php
      session_start();
      $userId = $_SESSION['user_id'];
      
      // Connect to the database and retrieve user details
      $connection = mysqli_connect('localhost', 'username', 'password', 'database');
      $query = "SELECT * FROM users WHERE id = $userId";
      $result = mysqli_query($connection, $query);
      $userDetails = mysqli_fetch_assoc($result);
      ?>
      
      <h1>User Profile: <?php echo $userDetails['username']; ?></h1>
      <form action="update_profile.php" method="post">
          <label for="email">Email:</label>
          <input type="text" id="email" name="email" value="<?php echo $userDetails['email']; ?>">
          <input type="submit" value="Update Profile">
      </form>
      
  7. PHP MySQL Display User Details with Role-Based Access:

    • Description: Display user details based on their role to implement role-based access control.
    • Code:
      <?php
      session_start();
      $userId = $_SESSION['user_id'];
      
      // Connect to the database and retrieve user details with role-based access
      $connection = mysqli_connect('localhost', 'username', 'password', 'database');
      $query = "SELECT * FROM users WHERE id = $userId AND role = 'admin'";
      $result = mysqli_query($connection, $query);
      $userDetails = mysqli_fetch_assoc($result);
      ?>
      
      <?php if ($userDetails): ?>
          <h1>Welcome, <?php echo $userDetails['username']; ?> (Admin)</h1>
          <p>Email: <?php echo $userDetails['email']; ?></p>
          <!-- Display other admin-specific details -->
      <?php else: ?>
          <p>You do not have permission to view this page.</p>
      <?php endif; ?>
      
  8. PHP MySQL Display User Details Using PDO:

    • Description: Display user details using PDO (PHP Data Objects) for database interactions.
    • Code:
      <?php
      session_start();
      $userId = $_SESSION['user_id'];
      
      // Connect to the database and retrieve user details using PDO
      $dsn = 'mysql:host=localhost;dbname=database';
      $username = 'username';
      $password = 'password';
      
      try {
          $pdo = new PDO($dsn, $username, $password);
          $query = "SELECT * FROM users WHERE id = :userId";
          $statement = $pdo->prepare($query);
          $statement->bindParam(':userId', $userId, PDO::PARAM_INT);
          $statement->execute();
          $userDetails = $statement->fetch(PDO::FETCH_ASSOC);
      } catch (PDOException $e) {
          die("Error: " . $e->getMessage());
      }
      ?>
      
      <h1>Welcome, <?php echo $userDetails['username']; ?></h1>
      <p>Email: <?php echo $userDetails['email']; ?></p>
      <!-- Display other user details as needed -->
      
  9. PHP MySQL Display User Details with JWT Authentication:

    • Description: Display user details using JSON Web Token (JWT) authentication for enhanced security.
    • Code:
      <?php
      require 'vendor/autoload.php'; // Include JWT library
      use Firebase\JWT\JWT;
      
      session_start();
      $userId = $_SESSION['user_id'];
      $secretKey = 'your-secret-key';
      
      // Connect to the database and retrieve user details with JWT authentication
      $connection = mysqli_connect('localhost', 'username', 'password', 'database');
      $query = "SELECT * FROM users WHERE id = $userId";
      $result = mysqli_query($connection, $query);
      $userDetails = mysqli_fetch_assoc($result);
      
      // Verify JWT token
      $jwt = $_COOKIE['jwt']; // Assuming the token is stored in a cookie
      try {
          $decoded = JWT::decode($jwt, $secretKey, array('HS256'));
          // Token is valid, continue displaying user details
      } catch (Exception $e) {
          header('Location: login.php'); // Redirect to login page if token is invalid
          exit();
      }
      ?>
      
      <h1>Welcome, <?php echo $userDetails['username']; ?></h1>
      <p>Email: <?php echo $userDetails['email']; ?></p>
      <!-- Display other user details as needed -->
      
  10. PHP MySQL Display User Details with Password Hashing:

    • Description: Display user details while ensuring secure password hashing for authentication.
    • Code:
      <?php
      session_start();
      $userId = $_SESSION['user_id'];
      
      // Connect to the database and retrieve user details with password hashing
      $connection = mysqli_connect('localhost', 'username', 'password', 'database');
      $query = "SELECT * FROM users WHERE id = $userId";
      $result = mysqli_query($connection, $query);
      $userDetails = mysqli_fetch_assoc($result);
      ?>
      
      <h1>Welcome, <?php echo $userDetails['username']; ?></h1>
      <p>Email: <?php echo $userDetails['email']; ?></p>
      <!-- Display other user details as needed -->
      

More Tags

build-process office-interop azure-keyvault opencv springfox classpath vhosts usage-statistics ringtone jsondecoder

More Programming Questions

More Gardening and crops Calculators

More Internet Calculators

More Mixtures and solutions Calculators

More Geometry Calculators