display username AFTER user has logged in PHP MySQL

133
May 01, 2018, at 05:06 AM

I've built a simple user register and login system, using PHP and bootstrap. I am a static designer so PHP is very new to me and I'm struggling with the syntax and logic so far, but I am enjoying it. I actually copied the PHP code from somewhere online but modified it to my project.

After a user logs in, he's directed to his profile page, profile.php

Once in profile page, I want it to say Welcome "firstname". At the moment it says Welcome "username". So somewhere in this code, I think the $username variable is being saved in the session.

I've read up how to do this and I think the logic is - the sessions should be created - the credentials should be saved in an array inside the session - you then call the firstname variable thusly:

<?php echo $_SESSION['firstname']; ?>

Here's my login.php code:

<?php include('../header/header.php') ?>
  <div class="container headingsrow">
      <div class="row">
      <div class="col-6 offset-3">
          <h2>Login</h2>
          <p>Already have an account set up? Log in with your details below:</p>
          <form method="post" action="login.php">
          <?php include('errors.php'); ?>
            <div class="form-group">
              <input type="text" name="username" value="<?php echo $username; ?>" class="form-control" id="inputUsername" placeholder="Email address">
            </div>
            <div class="form-group">
              <input type="password" name="password" value="<?php echo $username; ?>" class="form-control" id="inputPassword" placeholder="Password">
            </div>
            <button type="submit" class="btn btn-primary register" name="login_user">Login <i class="fas fa-sign-in-alt"></i></button>
            <a href="#"><p>Forgotten your password? </p></a><br><br>
          </form>
      </div> 

  </div>

here's my header.php code:

<?php
session_start();
 //After Login
 $_SESSION['id'] = 1;

// initializing variables
$firstname          = "";
$lastname           = "";
$username           = "";
$email              = "";
$telnumber          = "";
$addressline1       = "";
$addressline2       = "";
$city               = "";
$postcode           = "";
$errors = array(); 
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'registration');
// REGISTER USER
if (isset($_POST['reg_user'])) {
  // receive all input values from the form
  $firstname = mysqli_real_escape_string($db, $_POST['firstname']);
  $lastname = mysqli_real_escape_string($db, $_POST['lastname']);
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $email = mysqli_real_escape_string($db, $_POST['email']);
  $telnumber = mysqli_real_escape_string($db, $_POST['telnumber']);
  $addressline1 = mysqli_real_escape_string($db, $_POST['addressline1']);
  $addressline2 = mysqli_real_escape_string($db, $_POST['addressline2']);
  $city = mysqli_real_escape_string($db, $_POST['city']);
  $postcode = mysqli_real_escape_string($db, $_POST['postcode']);
  $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
  $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
  // form validation: ensure that the form is correctly filled ...
  // by adding (array_push()) corresponding error unto $errors array
  if (empty($firstname)) { array_push($errors, "First Name is required"); }
  if (empty($lastname)) { array_push($errors, "Last Name is required"); }
  if (empty($username)) { array_push($errors, "Username is required"); }
  if (empty($email)) { array_push($errors, "Email is required"); }
  if (empty($telnumber)) { array_push($errors, "Telephone number is required"); }
  if (empty($addressline1)) { array_push($errors, "Address line 1 is required"); }
  if (empty($addressline2)) { array_push($errors, "Address line 2 is required"); }
  if (empty($city)) { array_push($errors, "City is required"); }
  if (empty($postcode)) { array_push($errors, "Post code is required"); }
  if (empty($password_1)) { array_push($errors, "Password is required"); }
  if ($password_1 != $password_2) {
  array_push($errors, "The two passwords do not match");
  }
  // first check the database to make sure 
  // a user does not already exist with the same username and/or email
  $user_check_query = "SELECT * FROM users WHERE username='$username' OR email='$email' LIMIT 1";
  $result = mysqli_query($db, $user_check_query);
  $user = mysqli_fetch_assoc($result);
  if ($user) { // if user exists
    if ($user['username'] === $username) {
      array_push($errors, "Username already exists");
    }
    if ($user['email'] === $email) {
      array_push($errors, "email already exists");
    }
  }
  // Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
    $password = md5($password_1);//encrypt the password before saving in the database
    $query = "INSERT INTO users (firstname, lastname, username, email, telnumber, addressline1, addressline2, city, postcode, password) 
          VALUES('$firstname', '$lastname', '$username', '$email', '$telnumber', '$addressline1', '$addressline2', '$city', '$postcode', '$password')";
    mysqli_query($db, $query);
    $_SESSION['username'] = $username;
    $_SESSION['success'] = "You are now logged in";
    header('location: index.php');
  }
}
// ... 
// LOGIN USER
if (isset($_POST['login_user'])) {
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password']);
  if (empty($username)) {
    array_push($errors, "Username is required");
  }
  if (empty($password)) {
    array_push($errors, "Password is required");
  }
  if (count($errors) == 0) {
    $password = md5($password);
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $results = mysqli_query($db, $query);
    if (mysqli_num_rows($results) == 1) {
      $_SESSION['username'] = $username;
      //$_SESSION['success'] = "You are now logged in"  ;
      header('location: profile.php');
    }else {
      array_push($errors, "Wrong username/password combination");
    }
  }
}
?>

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="../assets/css/style.css">
    <script defer src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
    <title>Prospect Job Vacancies</title>
  </head>
  <body>
    <!-- start of Navbar -->
    <div class="container menubg">
      <div class="row">
        <div class="col">
          <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <a class="navbar-brand" href="http://vacancies.prospect.local/index.php"><img src="../assets/img/prospect_logo.jpg" class="logo"></a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
              <ul class="navbar-nav mr-auto">
                <li class="nav-item">
                  <a href="http://vacancies.prospect.local/index.php"><button type="submit" name="home" class="btn btn-primary">Home <i class="fas fa-home"></i></i></button></a>
                  <!-- <a class="nav-link" href="http://vacancies.prospect.local/registration/register.php">Register <span class="sr-only">(current)</span></a> -->
                </li>                
                <li class="nav-item">
                  <?php
                  if(isset($_SESSION['username'])){
                    echo "<a href=\"http://vacancies.prospect.local/registration/profile.php\"><button type=\"submit\" name=\"home\" class=\"btn btn-primary\">My Account <i class=\"far fa-user\"></i></button></a>";
                }else{
                echo "<a href=\"http://vacancies.prospect.local/registration/register.php\"><button type=\"submit\" name=\"home\" class=\"btn btn-primary\">Register <i class=\"fas fa-user-plus\"></i></i></i></button></a>";
                }
                ;?>  
                </li>                
                <li class="nav-item">
                  <?php
                  if(isset($_SESSION['username'])){
                    echo "<a href=\"http://vacancies.prospect.local/logout.php\"><button type=\"submit\" name=\"logout\" class=\"btn btn-primary\">Logout <i class=\"fas fa-sign-in-alt\"></i></button></a>";
                  }else{
                  echo "<a href=\"http://vacancies.prospect.local/registration/login.php\"><button type=\"submit\" name=\"login\" class=\"btn btn-primary\">Login <i class=\"fas fa-sign-in-alt\"></i></button></a>";
                  } 
                  ;?>
                  <!-- <a class="nav-link" href="http://vacancies.prospect.local/registration/register.php">Register <span class="sr-only">(current)</span></a> -->
                </li>
                  <!-- <a class="nav-link" href="http://vacancies.prospect.local/registration/register.php">Register <span class="sr-only">(current)</span></a> -->
              </ul>
              <span class="navbar-text">
                <a href="https://www.prospect.org.uk/"><i class="fas fa-sign-out-alt"></i> Return to main Prospect website</a>
              </span>
            </div>
          </nav>
          <!-- //end of Navbar -->
        </div>
      </div>
    </div>
    <!-- end of top menu div -->
    <div class="container-fluid jobbg">
      <div class="row">
        <div class="col">
            <div class="container title">
              <div class="row">
                <div class="col">
                  <h1 class="jobheading">Job opportunities with Prospect</h1>
                </div>
              </div>
            </div>
        </div>
      </div>
    </div>

So when I change this part in my profile.php code from:

<?php echo $_SESSION['username']; ?>

to

<?php echo $_SESSION['firstname']; ?>

I get this error:

Welcome 
Notice: Undefined index: firstname in 
C:\xampp\htdocs\vacancies\registration\profile.php on line 46
array(2) { ["id"]=> int(1) ["username"]=> string(11) "bum@bum.com" } 

Ultimately I want it to say Welcome "firstname".

Answer 1

All that means is $_SESSION['firstname'] is not defined, in which case you forgot to assign a value to $_SESSION['firstname'] upon user login.

in your header.php :

<?php
session_start();
...
// LOGIN USER
if (isset($_POST['login_user'])) {
  $username = mysqli_real_escape_string($db, $_POST['username']);
  $password = mysqli_real_escape_string($db, $_POST['password']);
  if (empty($username)) {
    array_push($errors, "Username is required");
  }
  if (empty($password)) {
    array_push($errors, "Password is required");
  }
  if (count($errors) == 0) {
    $password = md5($password);
    $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
    $results = mysqli_query($db, $query);
    if (mysqli_num_rows($results) == 1) {
      //fetch result into an associative array.
      $user = mysqli_fetch_assoc($results);
      //$_SESSION['firstname'] should go here
      $_SESSION['firstname'] = $user['firstname'];
      $_SESSION['username'] = $user['username'];
      //$_SESSION['success'] = "You are now logged in"  ;
      header('location: profile.php');
    }else {
      array_push($errors, "Wrong username/password combination");
    }
  }
}
Answer 2

you try add $_SESSION['firstname'] in here

if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
  $_SESSION['username'] = $username;
  $_SESSION['firstname'] = "HERE YOUR FIRST NAME";
  //$_SESSION['success'] = "You are now logged in"  ;
  header('location: profile.php');
}else {
  array_push($errors, "Wrong username/password combination");
}

}

READ ALSO
How to replace JSON key&#39;s value in mysql

How to replace JSON key's value in mysql

I have a mysql JSON column like:

148
EF: Incorrect usage of spatial/fulltext/hash index and explicit index order

EF: Incorrect usage of spatial/fulltext/hash index and explicit index order

I'm using Entity framework with my WEB Api projectI use code first migration

1678
Column name having @ symbol

Column name having @ symbol

I am executing a dynamically generated MySQL query using C# codeAn exception gets thrown:

147
bulk data insert in mysql - wallet program

bulk data insert in mysql - wallet program

I have a mysql table structure by the following image linkI need to update every user account with some amount with every purchase happen by the portal

185