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


#1

[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);
if($rows==1){
$_SESSION[‘zalogowany’]=TRUE;

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

haslo albo login piepoprawne


powrot zaloguj"; }[/php]

#2

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.


#3

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


#4

Do you know how to use sessions?

[php]

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

#5

However, the other example is more thorough:

[php]

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

#6

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


#7

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);
$stmt->store_result();
$rows = $stmt->num_rows;
$stmt->bind_result($email);

if($rows==1){
$_SESSION[‘zalogowany’]=TRUE;
$_SESSION[‘email’] = $email;
}
[/php]


#8

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