Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post full name drawn from MySQL using only username as login, in PHP?

SOLVED: After rewriting the mysql and membership code several times, the last one worked when mysqlind (native driver) was enabled.


I have this login script that works perfectly, but I want it to post to my pages the full name of the user that is logged in.

I want it to fetch and post, firstname and lastname in a div on any given page using the username given to session at login.

Login script:

<?php
session_start();

require_once 'classes/membership.php';
$membership = new Membership();

// If the user clicks "Log Out".
if(isset($_GET['status']) && $_GET['status'] == 'loggedout') {
$membership->log_User_Out();
}

// Did the user enter a password/username and click submit?
if($_POST && !empty($_POST['username']) && !empty($_POST['pwd'])) {
$response = $membership->validate_User($_POST['username'], $_POST['pwd']);
}
?>

Checking credentials in membership.php:

<?php

require 'mysql.php';

class Membership {

function validate_user($un, $pwd) {
    $mysql = New Mysql();
    $ensure_credentials = $mysql->verify_Username_and_Pass($un, md5($pwd));

    list($ensureCredentials, $data) = $mysql->verify_Username_and_Pass($un, md5($pwd));

if($ensure_credentials) {
    $_SESSION['status'] = 'authorized';
    $_SESSION['fname'] = $data['fname'];
    $_SESSION['lname'] = $data['lname'];
    header("location: medlem.php");
} else return "Please enter correct username and password";
    print_r($row);
    exit;

} 

function log_User_Out() {
    if(isset($_SESSION['status'])) {
        unset($_SESSION['status']);

        if(isset($_COOKIE[session_name()])) 
            setcookie(session_name(), '', time() - 1000);
            session_destroy();
    }
}

function confirm_Member() {
    session_start();
    if($_SESSION['status'] !='authorized') header("location: login.php");
}

}

Establishing connection to mysql in mysql.php:

<?php

require_once 'includes/constants.php';

class Mysql {
private $conn;

function __construct() {
    $this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or 
                  die('There was a problem connecting to the database.');
}

function verify_Username_and_Pass($un, $pwd) {

$query = "SELECT *
        FROM users
        WHERE username = ? AND password = ?
        LIMIT 1";

if($stmt = $this->conn->prepare($query)) {
    $stmt->bind_param('ss', $un, $pwd);
    $stmt->execute();
    // UPDATE : I added correct usage of the stmt here.    
    $result = $stmt->get_result();
    if($row = $result->fetch_array()) {
       $stmt->free_result();
       $stmt->close();                
        // returning an array the first item is the validation the second is the data. 
        return array(true, $row);
    }
}
// if there is no just return empty data, and false for validation.
return array(false, array());
}

And for the sake of re-usability I define constants in constants.php:

<?php

// Define constants here

define('DB_SERVER', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypassword');
define('DB_NAME', 'membership');

How can I easily get it to retrieve firstname (fname) and lastname (lname) from MySQL database, when the session only knows the username of the logged in user.

As I stated above the row names for first and last name are fname and lname.

I want to display it as easy as possible with a floating CSS formated div id'ed topr, like so:

<?php 
session_start();
if(isset($_SESSION['status'])){
    echo "<div id='topr'>Welcome, " . $_SESSION['fname'] . "!</div>";
} ?>

I mainly focus on displaying the firstname first. By the time I get that right I will surely have it display lastname to.

Just want to learn more about this. As my web searches didn't come up with anything that I could manage to implement in my code without messing something up.

like image 206
Johannes Mehl Avatar asked Sep 26 '22 03:09

Johannes Mehl


1 Answers

Change your verify function as follow. I added related comments.

function verify_Username_and_Pass($un, $pwd) {

    $query = "SELECT *
            FROM users
            WHERE username = ? AND password = ?
            LIMIT 1";

    if($stmt = $this->conn->prepare($query)) {
        $stmt->bind_param('ss', $un, $pwd);
        $stmt->execute();
        // UPDATE : I added correct usage of the stmt here.    
        $result = $stmt->get_result();
        if($row = $result->fetch_array()) {
           $stmt->free_result();
           $stmt->close();                
            // returning an array the first item is the validation the second is the data. 
            return array(true, $row);
        }
    }
    // if there is no just return empty data, and false for validation.
    return array(false, array());
}

So in your MemberShip class where you call verify_Username_and_Pass just get the array data in to variables. and use it send to session variables. So you will be eligible to use session in where ever you wanted.

   list($ensureCredentials, $data) = $mysql->verify_Username_and_Pass($un, md5($pwd));
   if($ensure_credentials) {
        $_SESSION['status'] = 'authorized';
        $_SESSION['first_name'] = $data['first_name'];
        $_SESSION['last_name'] = $data['last_name'];
        header("location: medlem.php");
    } else return "Please enter correct username and password";
like image 127
FZE Avatar answered Oct 12 '22 23:10

FZE