how to get data from db when login and store in Session to use it on other pages


[php] $query = “SELECT * FROM rejestracja WHERE login=’$login’ AND haslo=’$haslo’”;
$result = mysqli_query($connection,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);

        $_SESSION['email'] = "witamy";
   header("Location: usercart.php");
echo "<div class='form'>

haslo albo login piepoprawne

powrot zaloguj"; }[/php]


First and foremost, use prepared statements. Doesn’t matter if done using mysqli or PDO, though PDO is easier and more mobile, but use them.

Next create a user class. When you pull the data from the record, it should propagate the user class and you just assign the user to the session.


I will use prepared statements I just need some data from DB to use it as a session. Thank you


Do you know how to use sessions?


<?php session_start(); if( isset($_SESSION['name'])){ echo "Hello " . htmlentities($_SESSION['name']); } else { $_SESSION['name'] = 'Harry'; } [/php]


However, the other example is more thorough:


<?php // semi pseudo code class Employee { public $empID; public $firstname; public $lastname; public function __constructor($id, $first, $last){ $this->empID = $id; $this->firstname = $first; $this->lastname = $last; } } class EmployeeRepository{ private $_pdo; public function __constructor($pdo){ $this->_pdo = $pdo; } public function getEmpById($id){ $sql = "SELECT id, first_name firstname, last_name lastname FROM Employees WHERE id = ?"; $stmt =$this->_pdo->prepare($sql); $stmt->execute([$id]); $emp = new Employee($stmt->fetch(PDO::FETCH_OBJECT)); return $emp; } } $empRepo = new EmployeeRepository($pdo); $_SESSION['employee'] = $empRepo->getEmpById(1); [/php]


I have session on other pages. I know excatly how to use is , the only problem is to take it from DB :slight_smile:


Change this,
[php]SELECT * FROM rejestracja[/php]
Actually name the columns you want to pull out.

Now, assuming you have a column ‘email’, you can do something like this,

[php]$query = “SELECT email FROM rejestracja WHERE login= ? AND haslo= ?”;
$stmt = $connection->prepare($query);
$stmt->bind_param(“ss”, $login, $haslo);
$rows = $stmt->num_rows;

$_SESSION[‘email’] = $email;


Also you should not store passwords (haslo) in plain text, it’s up there with the worst things you can do as a web dev.

Use password_hash / password_verify