简体   繁体   中英

PDO Login get Username

How do i echo out the Username when they got access to Admin.php? I've tried to like include the files and made others sessions and such but it doesn't work. User.php:

<?php 
session_start();
include_once("anslutning.php");


class User{

    private $db;

    public function __construct(){
        $this->db = new Anslutning();
        $this->db = $this->db->dbConnect();

        }
    public function Login($username, $password){
        if(!empty($username) && !empty($password)) {
            $st = $this->db->prepare("select * from users where username =? and password=?");
            $st->bindParam(1, $username);
            $st->bindParam(2, $password);
            $st->execute();

            if($st->rowCount() == 1) {
                header("Location: admin.php");
                $_SESSION['inloggad']="true";

                }else {
                    echo "Fel Användarnamn eller Lösenord!";
                    }


            }else {
                echo "Var vänlig och skriv in ett Användarnamn och Lösenord!";
                }



        }





    }



?>

Admin.php

<?php
session_start();
if($_SESSION['inloggad']!="true") {
    header ("Location: loggain.php");
    }
 ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head> 
    <?php include "../include/head.php" ?>
    <title>Swebby | Admin</title>
</head>
<body>
    <div class="container">
        <a href="loggaut.php">Logga UT</a>
    </div>
</body>
</html>

So my question is.. How do i make it echo out the username on the Admin,php? Thanks!!

There are few things you need to look at.

  1. Place this $row = $st->fetch(PDO::FETCH_ASSOC); underneath $st->execute();
  2. Create a session for your username when the user logs in.
    Place $_SESSION['username'] = $row['username']; underneath $_SESSION['inloggad']="true";
    This assumes "username" is the name of the username field in your database

Then you can echo the username like this <?php echo $_SESSION['username'] ?>

Happy Coding !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM