用户登录PHP MySQL后显示用户名

时间:2018-04-30 14:26:36

标签: php mysql

我使用PHP和bootstrap构建了一个简单的用户注册和登录系统。我是一名静态设计师,所以PHP对我来说是一个新手,我到目前为止都在努力学习语法和逻辑,但我很享受。我实际上从在线某处复制了PHP代码,但将其修改为我的项目。

用户登录后,他将被定向到他的个人资料页面profile.php

一旦进入个人资料页面,我希望它说欢迎"名字"。目前它说欢迎"用户名"。所以在这段代码的某处,我认为$ username变量正在会话中保存。

我已经读过如何做到这一点,我认为逻辑是 - 应该创建会话 - 凭证应该保存在会话内的数组中 - 然后你就这样调用firstname变量:

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

这是我的login.php代码:

<?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>

这是我的header.php代码:

<?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>

所以当我在我的profile.php代码中更改此部分时:

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

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

我收到此错误:

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" } 

最终我希望它说欢迎&#34;名字&#34;。

2 个答案:

答案 0 :(得分:0)

所有这些意味着 $ _ SESSION ['firstname'] 未定义,在这种情况下,您忘记为 $ _ SESSION ['firstname'] 分配值用户登录。

你的header.php中的

{{1}}

答案 1 :(得分:-1)

您尝试在此处添加$_SESSION['firstname']

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");
  }
}