使用PHP PDO / Function从数据库中获取特定行

问题描述 投票:0回答:1

我有问题用下一个代码显示数据库中的其他行。当我输入<?php echo $_SESSION['username']; ?>时,我在home.php上获得登录用户的用户名,但是当我想使用相同代码<?php echo $_SESSION['company']; ?>从数据库中显示用户公司时,我没有在home.php上获得该行。我的代码看起来像这样:

config.php文件

<?php
ob_start();
session_start();

date_default_timezone_set('Europe/London');

define('DBHOST','host');
define('DBUSER','user');
define('DBPASS','pass');
define('DBNAME','dbname');

define('DIR','localhost');
define('SITEEMAIL','[email protected]');

try {
    $db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo '<p class="bg-danger">'.$e->getMessage().'</p>';
    exit;
}

include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?>

user.php的

<?php
    include('password.php');
    class User extends Password{

        private $_db;

        function __construct($db){
            parent::__construct();

            $this->_db = $db;
        }

        private function get_user_hash($username){

            try {
                $stmt = $this->_db->prepare('SELECT password, username, memberID FROM tableName WHERE username = :username AND active="Yes" ');
                $stmt->execute(array('username' => $username));

                return $stmt->fetch();

            } catch(PDOException $e) {
                echo '<p class="bg-danger">'.$e->getMessage().'</p>';
            }
        }

        public function login($username,$password){

            $row = $this->get_user_hash($username);

            if($this->password_verify($password,$row['password']) == 1){

                $_SESSION['loggedin'] = true;
                $_SESSION['username'] = $row['username'];
                $_SESSION['memberID'] = $row['memberID'];
                return true;
            }
        }

        public function logout(){
            session_destroy();
        }

        public function is_logged_in(){
            if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
                return true;
            }
        }
    }
?>

home.php

<?php
    require('includes/config.php');
    if(!$user->is_logged_in()){ header('Location: login.php'); }
?>

在我希望显示用户信息时,我输入此行代码:

<?php echo $_SESSION['username']; ?> **WORKING**

<?php echo $_SESSION['company']; ?> **NOT WORKING**

我认为问题是某些功能或需要创建另一个功能来从数据库中检索所有字段,但如果有人可以帮助我,这将是伟大的。谢谢大家

php pdo
1个回答
0
投票

请参阅以下更新的qazxsw poi。问题是,你没有从qazxsw poi中选择列qazxsw poi而不是设置会话。

user.php
© www.soinside.com 2019 - 2024. All rights reserved.