【问题标题】:Storing Variables in Database class在数据库类中存储变量
【发布时间】:2015-12-01 22:59:39
【问题描述】:

我是 PHP OOP 的新手,并且已经编写了一些代码,用于使用 PHP OOP 在数据库中存储一些产品。我正在尝试将我的用户名和密码存储在我的数据库类的会话变量中。这是我的数据库类的代码以及我的登录表单的代码。运行时出现以下错误。

解析错误:语法错误,第 9 行 C:\xampp\htdocs\wdv341\php-oop-crud-level-3\config\database.php 中出现意外的“$_SESSION”(T_VARIABLE)

数据库.php

<?php


class Database{

    // specify your own database credentials
    private $host = "localhost";
    private $db_name = "wdv341";
    private $username = $_SESSION['username'];
    private $password = $_SESSION['password'];
    public $conn;

    // get the database connection
    public function getConnection(){

        $this->conn = null;

        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }



}

?>

userLogin.php

<?php
session_cache_limiter('none');          //This prevents a Chrome error when using the back button to return to this page.
session_start();


if (isset($_POST['username']) && isset($_POST['password'])) //This is a valid user.  Show them the Administrator Page
    {

$_SESSION['username']=$_POST['username'];   //pull the username from the form
$_SESSION['password']=$_POST['password'];

//var_dump($_SESSION);

include_once 'config/database.php';

 if (isset($_SESSION['username']) && ($_SESSION['password'])){

header("location:read_categories.php");

}

else
{
?>
<html>
<body>
                <h2>Please login to the Administrator System</h2>
                <form method="post" name="loginForm" action="userLogin.php" >
                  <p>Username: <input name="username" type="text" /></p>
                  <p>Password: <input name="password" type="password" /></p>
                  <p><input name="submitLogin" value="Login" type="submit" /> <input name="" type="reset" />&nbsp;</p>
                </form>
</body>  
</html>
<?php
}
?>

请帮忙!!

【问题讨论】:

    标签: php


    【解决方案1】:

    错误意味着它在第 9 行遇到了$_SESSION[],我假设大致在这里:

    private $username = $_SESSION['username'];
    

    此时您无法引用$_SESSIONFrom the docs:

    ...这个声明可能包含一个初始化,但是这个初始化必须是一个常量值——也就是说,它必须能够在编译时被评估并且不能依赖于运行时信息 以便被评估。

    您可以在创建类的实例时使用constructor 设置该值:

    class Database {
        private $username;
    
        public function __construct() {
            $this->username = $_SESSION['username'];
        }
    }
    

    【讨论】:

    • 非常感谢您的修复!!
    猜你喜欢
    • 2018-08-13
    • 2019-12-31
    • 1970-01-01
    • 2017-06-29
    • 2018-08-13
    • 1970-01-01
    • 2015-10-09
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多