在数据库类中存储变量

时间:2015-12-01 22:59:40

标签: php

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

解析错误:语法错误,意外' $ _会话'第9行的C:\ xampp \ htdocs \ wdv341 \ php-oop-crud-level-3 \ config \ database.php中的(T_VARIABLE)

database.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;
    }



}

&GT;

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
}
?>

请帮助!!

1 个答案:

答案 0 :(得分:1)

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

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

此时您无法引用$_SESSIONFrom the docs

  

...此声明可能包含初始化,但此初始化必须是常量值 - 也就是说,它必须能够在编译时进行评估,并且不能依赖于运行时信息为了进行评估。

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

class Database {
    private $username;

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