简体   繁体   English

如何从 PHP 中的 mysql 数据库获取用户 ID?

[英]How can I get the user ID from mysql database in PHP?

I'm trying to have the ID of the current logged user.我正在尝试获取当前登录用户的 ID。 But I only manage to get the ID of all users但我只能设法获得所有用户的ID

I've got this in my model.php我在我的model.php 里有这个

    public function listUsers() {
        $this->open();
        $stmt = $this->pdo->prepare("SELECT * FROM users");
        $stmt->execute();
        return $stmt->fetchAll();
    }

I have this in my controller: users.php我的 controller 中有这个: users.php

<?php
class Users {

    private $model;
    public function loadModel($model) {
        $this->model=$model;
    }

    public function view() {
        global $users; 
        $users=$this->model->listUsers(); 
        require "../app/view/_templates/header.php";
        require "../app/view/listUsers.php";
        require "../app/view/_templates/footer.php";
    }
}

And on my page I have this:在我的页面上我有这个:

<?php 
            global $users;
            foreach ($users as $user)
            echo $user["id"]; ?>

So it echo all users but not only the one logged.因此它会回显所有用户,而不仅仅是记录的用户。 I've tried just "echo $user[id]" but doesnt work.我只试过“echo $user[id]”但没有用。 $_SESSION["id"] doesnt work either $_SESSION["id"] 也不起作用

Any ideas?有任何想法吗?

Thank you:)谢谢:)

Is the logged in user's ID saved in the $_SESSION["id"] ?登录用户的 ID 是否保存在$_SESSION["id"]中? You should have a if statement where you filter the user to the logged in ID if you only want the logged in user ID.如果您只想要登录的用户 ID,则应该有一个 if 语句,您可以在其中将用户过滤为登录的 ID。

Example:例子:

<?PHP
global $users;
foreach($users as $user) {
  if($_SESSION["id"] == $user["id"]) {
    echo $user["id"]
  }
}

Depending on the usage, you could also implement a WHERE statement in your SQL statement where you specify a user ID (example: SELECT * FROM users WHERE id = '$userid' ).根据用途,您还可以在指定用户 ID 的 SQL 语句中实施 WHERE 语句(示例: SELECT * FROM users WHERE id = '$userid' )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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