【问题标题】:trying to get property 'username' of non-object in home.php file试图在 home.php 文件中获取非对象的属性“用户名”
【发布时间】:2022-07-25 17:01:56
【问题描述】:

在我的 PHP 项目中,我想获取登录的用户数据,登录后我将重定向到主页。PHP 页面,我无法访问 $user 数据,这是我的代码,任何有此经验的人错误请帮助我 在我的 user.PHP 文件中

<?php

class User{
    public $db,$id;

    public function __construct(){
        $db = new DB;

        $this->db =  $db->connect();
        $this->id = $this->ID();
    }
    public function ID(){
        if($this->isLoggedIn()){
            return $_SESSION['id'];
        }
    }
    public function emailExist($email){
        $stmt = $this->db->prepare("SELECT *FROM `users` WHERE `email`=:email ");
        $stmt->bindParam(":email",$email,PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_OBJ);
        if (!empty($user)) {
            return $user;
        }else{
            return false;
        }


    }
    public function userData($id=''){
        $id = ((!empty($id)) ? '$id' : '$this->id');
        $stmt = $this->db->prepare("SELECT *FROM `users` WHERE `id`=:id ");
        $stmt->bindParam(":id",$id,PDO::PARAM_STR);
        $stmt->execute();
         return $stmt->fetch(PDO::FETCH_OBJ);
        
    }

    public function isLoggedIn(){
        return ((isset($_SESSION['id'])) ? true : false);
    }

}

在我的 home.php 中

include_once 'session.php';
include_once 'connection.php';
include_once 'utilities.php';
include_once 'user.php';

if(!$userObj->isLoggedIn()){
    $userObj->redirect('index.php');
}
$user = $userObj->userData();

?>
<div>
                        <span class="font-medium select-none"><?php echo $user->username;?></span>
                    </div>

在我的 session.php 中

<?php
session_start();
require 'connection.php';
require 'user.php';

$userObj = new User;

define('BASE_URL','http://localhost:8081/insa/');

【问题讨论】:

    标签: php


    【解决方案1】:

    我的猜测是您的 $userObj 包含 FALSE,因为找不到请求的数据。在你使用它之前尝试var_dump($userObj);,看看它有什么价值。

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 2019-05-23
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 2019-12-13
      • 2020-01-17
      相关资源
      最近更新 更多