如何获取已登录用户php的ID

时间:2020-02-25 18:04:29

标签: php mysql

嗨,我是php的新手,我正在使用php和phpmyadmin作为服务器来创建预订系统数据库和网站。我需要数据库编码方面的帮助。

具体地说,我正在尝试获取已登录用户的ID。

这是我的代码

// connect to database
$db = mysqli_connect('localhost', '#', '#', '#'); // hidden for security 

// variable declaration
$username = "";
$email    = "";
$errors   = array(); 

// call the register() function if register_btn is clicked
if (isset($_POST['register_btn'])) {
    register();
}

// call the login() function if register_btn is clicked
if (isset($_POST['login_btn'])) {
    login();
}

if (isset($_GET['logout'])) {
    session_destroy();
    unset($_SESSION['user']);
    header("location: login.php");
}

if (isset($_POST['pickup_date'])) {
    book();

}

// REGISTER USER
function register(){
    global $db, $errors;

    // receive all input values from the form
    $firstname    =  e($_POST['firstname']);
    $surname      =  e($_POST['surname']);
    $address      =  e($_POST['address']);
    $home_postcode = e($_POST['home_postcode']);
    $age        =  e($_POST['age']);
    $email       =  e($_POST['email']);
    $username    =  e($_POST['username']);
    $password_1  =  e($_POST['password_1']);
    $password_2  =  e($_POST['password_2']);

    // form validation: ensure that the form is correctly filled
    if (empty($firstname)) { 
        array_push($errors, "first name is required"); 
    }
    if (empty($surname)) { 
        array_push($errors, "surname is required"); 
    }
    if (empty($address)) { 
        array_push($errors, "address is required"); 
    }
    if (empty($home_postcode)) { 
        array_push($errors, "home postcode is required"); 
    }
    if (empty($age)) { 
        array_push($errors, "age is required"); 
    }
    if (empty($email)) { 
        array_push($errors, "Email is required"); 
    }
    if (empty($username)) { 
        array_push($errors, "Username 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");
    }


    $password = $password_1;
    // register user if there are no errors in the form
    if (count($errors) == 0) {

        if (isset($_POST['user_type'])) {
            $user_type = e($_POST['user_type']);
            $query = "INSERT INTO users (firstname, surname, address, home_postcode, age, email, username, user_type, password) 
                      VALUES('$firstname', '$surname', '$address', '$home_postcode','$age','$email', '$username', '$user_type', '$password')";
            mysqli_query($db, $query);
            $_SESSION['success']  = "New user successfully created.";
            header('location: home.php');
        }else{
            $query = "INSERT INTO users (firstname, surname, address, home_postcode, age, email, username, user_type, password) 
                      VALUES('$firstname', '$surname', '$address', '$home_postcode','$age','$email', '$username', 'user', '$password')";
            mysqli_query($db, $query);

            // get id of the created user
            $logged_in_user_id = mysqli_insert_id($db);

            $_SESSION['user'] = getUserById($logged_in_user_id); // put logged in user in session
            $_SESSION['success']  = "You are now logged in";
            header('location: index.php');              
        }

    }

}

// BOOK A CAR
function book() {
    global $db, $errors;

    // receive all input values from the form
    $car_chosen     =  e($_POST['car_chosen']);
    $pickup_date    =  e($_POST['pickup_date']);
    $pickup_time    =  e($_POST['pickup_time']);
    $return_date    =  e($_POST['return_date']);
    $return_time    = e($_POST['return_time']);
    $collection_postcode =  e($_POST['collection_postcode']);

    // form validation: ensure that the form is correctly filled
    if (empty($pickup_date)) { 
        array_push($errors, "pickup date is required"); 
    }
    if (empty($pickup_time)) { 
        array_push($errors, "pickup time is required"); 
    }
    if (empty($return_date)) { 
        array_push($errors, "return date is required"); 
    }
    if (empty($return_time)) { 
        array_push($errors, "return time is required"); 
    }
    if (empty($collection_postcode)) { 
        array_push($errors, "collection postcode is required"); 
    }

    // convert car chosen to the ID of that car 
    $query = "SELECT * FROM cars WHERE car_ID = " . $car_chosen;

    // book car if there are no errors in the form
    if (count($errors) == 0) {
            $query = "INSERT INTO booking_details (pickup_date, pickup_time, return_date, return_time, total_cost, collection_postcode, car_fk, user_fk) 
                      VALUES('$pickup_date', '$pickup_time', '$return_date', '$return_time', '1000', '$collection_postcode','$car_chosen','$id')";
            if(mysqli_query($db, $query)){
                echo 'hello';                   
            }else{
                echo "<br>" . $query . "<br>";
                echo mysqli_error($db); 
            }

    }

}

// return user array from their id
function getUserById($id){
    global $db;
    $query = "SELECT * FROM users WHERE user_id=" . $id;
    $result = mysqli_query($db, $query);

    $user = mysqli_fetch_assoc($result);
    return $user;
}

// LOGIN USER
function login(){
    global $db, $username, $errors;

    // grab form values
    $username = e($_POST['username']);
    $password = e($_POST['password']);

    // make sure form is filled properly
    if (empty($username)) {
        array_push($errors, "Username is required");
    }
    if (empty($password)) {
        array_push($errors, "Password is required");
    }

    // attempt login if no errors on form
    if (count($errors) == 0) {

        $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
        $results = mysqli_query($db, $query);

        if (mysqli_num_rows($results) == 1) { // user found
            // check if user is admin or user
            $logged_in_user = mysqli_fetch_assoc($results);
            if ($logged_in_user['user_type'] == 'admin') {

                $_SESSION['user'] = $logged_in_user;
                $_SESSION['success']  = "You are now logged in";
                header('location: home.php');         
            }else{
                $_SESSION['user'] = $logged_in_user;
                $_SESSION['success']  = "You are now logged in";

                header('location: index.php');
            }
        }else {
            array_push($errors, "Wrong username/password combination");
        }
    }
}

function isLoggedIn()
{
    if (isset($_SESSION['user'])) {
        return true;
    }else{
        return false;
    }
}

function isAdmin()
{
    if (isset($_SESSION['user']) && $_SESSION['user']['user_type'] == 'admin' ) {
        return true;
    }else{
        return false;
    }
}

// escape string
function e($val){
    global $db;
    return mysqli_real_escape_string($db, trim($val));
}

function display_error() {
    global $errors;

    if (count($errors) > 0){
        echo '<div class="error">';
            foreach ($errors as $error){
                echo $error .'<br>';
            }
        echo '</div>';
    }
}

因此,我需要在他们登录后收集用户ID。我还需要它在首次注册后可以在用户登录的地方使用。

我不知道如何获得它,我只设法获得了所选汽车的ID。收集到user_id之后,我应该可以将其与其余值一起插入booking_details表中。

其他一切都正常。

感谢所有帮助。

2 个答案:

答案 0 :(得分:0)

您应该从会话中获取用户详细信息

$user = $_SESSION['user'];
$loggeduserid = $user['id'];

注意:此处id是用户表的列名

答案 1 :(得分:-1)

您要将整行数据(数组)转储到$session['user']

$logged_in_user = mysqli_fetch_assoc($results);
$_SESSION['user'] = $logged_in_user;

因此,您应该仅能够使用ID列名称获取登录用户的ID。

$loggedInUserId = $_SESSION['user']['name_of_id_column'];

最后,我应该说清楚。您没有以安全的方式使用SQL。正如评论者所建议的那样,请研究PDO和准备好的声明。这比您想像的要容易。 https://phpdelusions.net/pdo