Jump to content

PDO user id session


Slam

Recommended Posts

Hey,
 
I'm trying to echo out user info based on user $_SESSION['user_id'], but session is not set, it says "Undefined index: user_id". Login works, but user_id is not set.
 
Class
class User {
	public $uid = "";

	public function userInfo($user_id) {
		global $db;

		$query = $db->prepare("SELECT `user_id`, `username`, `email` FROM `users` WHERE `user_id` = :id");
		$query->bindValue(':id', $user_id);
		$query->execute();

		return $query->fetch();
	}

	public function login($login, $password){
		global $db;

		$query = $db->prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :user AND `password` = :pass OR `email` = :user AND `password` = :pass");
		
		$query->bindValue(':user', $login);
		$query->bindValue(':pass', $password);
		$query->execute();
		
		$result = (bool) $query->fetchColumn(0);

		if($result) {
			$this->uid = $result['user_id'];
		} 

		return $result;
	}

}

Login

<?php
if (isset($_POST['login'], $_POST['password'])) {

	$login = $_POST['login'];
	$password = sha1($_POST['password']);
	
	$errors = array();

	if (empty($login) || empty($password))
	{
	 $errors[] = 'All fields required!';
	} 
	else {

		$user = new User;
		$log_in = $user->login($login, $password); 
			if ($log_in) 
			{ 
				$_SESSION['user_id'] = $user->uid; 
				header('Location: account.php');
				exit();

			} else { 
				$errors[] = 'Username/Email or password incorrect!';
			}
	}
	
	if (!empty($errors)){
		
			foreach ($errors as $error)
			{
				echo '<div id="error"><strong>', $error, '</strong></div><br />';
			}
		}
}
?>

Account page

$user_id = $_SESSION['user_id'];
$user = new User;
$data = $user->userInfo($user_id);
echo $data['username'],'<br />';
echo $data['email'],'<br />';

echo '<pre>';
print_r($_SESSION['user_id']);
echo '</pre>';

if(isset($_SESSION['user_id'])){
	
	$user_id = $_SESSION['user_id'];
	$data = $user->userInfo($user_id);
	
	echo '<pre>';
	print_r($data);
	echo '</pre>';
	echo $data['username'],'<br />';

}else {
	echo 'bla';
}

 

 

Link to comment
Share on other sites

1) You must have a session_start() before sending any output and before referring to $_SESSION. I can't tell if there is one in your code.

 

2) Turn on error reporting at the beginning of your code

error_reporting(E_ALL);
ini_set('display_errors', 1);
3) This code is not doing what you think (I think)

 

 

	$query->execute();

	$result = (bool) $query->fetchColumn(0);

	if($result) {
		$this->uid = $result['user_id'];
	} 

	return $result;

 

 

By casting $result to a BOOL, $result will NOT be an array. So, your assignment inside the IF statement is not valid, and should be producing an error (Warning).
Link to comment
Share on other sites

1. I do have session_start();

2. Still "Notice: Undefined index: user_id"

3. I tried 

	public function login($login, $password){
		global $db;

		$query = $db->prepare("SELECT COUNT(*) FROM users WHERE username = :user AND password = :pass OR email = :user AND password = :pass");
		
		$query->bindValue(':user', $login);
		$query->bindValue(':pass', $password);
		$query->execute();
		$result = $query->fetchColumn();

		return $result;
	}
$user = new User;
		$log_in = $user->login($login, $password); 
		if($log_in) {
			$_SESSION['user_id'] = $log_in;
			header('Location: account.php');
			exit();
		}

 

but still "Notice: Undefined index: user_id" when I try echo out user info.

Link to comment
Share on other sites

Sorry, I never really looked at the query:

 

 

	$query = $db->prepare("SELECT COUNT(*) FROM users WHERE username = :user AND password = :pass OR email = :user AND password = :pass");

 

 

You are not selecting the user_id column, you are only selecting the number of rows that match. So, change the query to select the user_id.

 

Then you need to check (after execute) if there are any rows in the result set. If not, the login is invalid (return false). If there are, you can fetch the row and return the user_id column.

Link to comment
Share on other sites

Coincidentally, I am having a similar (if not the same) problem. I have tested my code as well as could be, so I know that it does work as it should (pardon the idiom, but you know what I mean) however the session array is not maintaining it's variables. Apologies if I'm intruding on this post but this could shed some light on the issue...as well as allow me to piggyback on the responses


   I am not going to post any code but rather a schema, this may make things clearer:


   starting with First.php:

   --this contains a form that uploads a username,password and file, begins with <?php session_start(); ?><html>...</html>

   --method=POST action=Second.php


  at Second.php:

  --begins with session_start();

  --correctly passes username and password and connects to the database using mysqli_connect();

  --parses the file passed and checks the contents against the database(anything that exists in both is saved in an array: lets call that duplicates)

  --now in the $_SESSION array we save username, password, and duplicates

  --a new form 'update.php' is included

  --a hidden variable from the form is checked to see if the form was submitted NOTE: this creates the undefined index error

  --Second.php should continue, if the variable is set, to process the new data. 

  -- the session is destroyed and the connection is closed


  in update.php

  -- session_start is called

  -- a form presents the values of the duplicates array and allows the user to select which to update in the database

  --method=post action=""


comments

so here is the blue print, I will post the code if preffered. but I have some observances of what is going on. After the include, the script continues to execute before presenting the form. If there is ANY WAY to pause a script, this would solve all my issues... I have even tried to sleep through a loop but this will not work as the script does not show the include until after the script has finished. anyhow, script executes and closes the database connection but does not destroy the session(this is certain as each script shows the same session id throughout). finally, the crux is that the $_SESSION array is empty after the update.php form submits... insight?

Link to comment
Share on other sites

Sorry, I never really looked at the query:You are not selecting the user_id column, you are only selecting the number of rows that match. So, change the query to select the user_id.

 

Then you need to check (after execute) if there are any rows in the result set. If not, the login is invalid (return false). If there are, you can fetch the row and return the user_id column.

 

I tried this but still "Notice: Undefined index: user_id"

	public function login($login, $password){
		global $db;

		$query = $db->prepare("SELECT COUNT(`user_id`) as `count`, `user_id` FROM `users` WHERE `username` = :user AND `password` = :pass OR `email` = :user AND `password` = :pass");
		
		$query->bindValue(':user', $login);
		$query->bindValue(':pass', $password);
		$query->execute();
		
		$result = $query->fetchColumn();
		if ($result) {  
			$this->uid = $result['user_id'];
		}

		return $result;
	}

 

and login

$user = new User;
$log_in = $user->login($login, $password); 
if($log_in) {
    $_SESSION['user_id'] = $user->uid;
    header('Location: account.php');
    exit();
}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.