Reputation: 1
I am new to Php OOP and have written some code for storing some product in a database using PHP OOP. I am tring to store my username and password in a session variable in my database class. Here is my code for my database class as well as what I have for my login form. I am getting the following error when I run it.
Parse error: syntax error, unexpected '$_SESSION' (T_VARIABLE) in C:\xampp\htdocs\wdv341\php-oop-crud-level-3\config\database.php on line 9
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;
}
}
?>
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" /> </p>
</form>
</body>
</html>
<?php
}
?>
Please Help!!
Upvotes: 0
Views: 71
Reputation: 39458
The error means it ran into $_SESSION[]
on line 9, which I assume is roughly here:
private $username = $_SESSION['username'];
You can't reference $_SESSION
at this point. From the docs:
... This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
You can use a constructor to set that value when an instance of the class is created instead:
class Database {
private $username;
public function __construct() {
$this->username = $_SESSION['username'];
}
}
Upvotes: 1