Search code examples
phpsqlsessionlogin-control

php - sql, get user id after login form by using $_session


i am try to assign the user id in a $_session after login from login page. I have read many posts here but i can unterstand how its work.

Here is my db structure

Here is my code from login.php

<?php
session_start(); //Έναρξη session
require_once('connect.php'); //καλώ το αρχείο
//Τι γίνετε όταν submitted η φόρμα
if(isset($_POST) & !empty($_POST)){

//Αναθέση τιμών μεταβλητών από τα inputs
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = md5($_POST['password']);

//Έλεγχος αν υπάρχουν τα στοιχεία σύνδεσης στην βάση
$sql = "SELECT * FROM `usermanagement` WHERE username ='$username' AND password='$password'";

$result = mysqli_query($connection, $sql);
$count = mysqli_num_rows($result);
if($count == 1){
    $_SESSION['username'] = $username;
    $_SESSION['UserId'] = $userid; // <-trying to determine this variable
}else{
    $fmsg = "Λάθος Όνομα Χρήστη ή Κωδικό χρήστη. ";
}
}
?>

i saw that $_SESSION['username'] = $username; but i don' t know how to do something similar for $_SESSION['userid'] = $userId;

Any help? Even a link.


Solution

  • You need to fetch the results from the sql query and use that to get the userid

    if( $count == 1 ){
    
        /* there is a recordset so fetch into as array */
        $row=mysqli_fetch_assoc( $result );
    
        /* extract the required variables from recordset array */
        $userid=$row['userid'];
    
        $_SESSION['username'] = $username;
        $_SESSION['UserId'] = $userid; // <-this variable should now exist
    
    }else{
        $fmsg = "Λάθος Όνομα Χρήστη ή Κωδικό χρήστη. ";
    }