0

I want to get the id in users table as a PHP session variable called $_SESSION['id']. But when I am printing the session variable, I have got Undefined index as the output.

Here is my PHP code.

$jsqla = mysql_query("select id, user_name, user_type from users where pw='$pass' and email='$email'") or die("Website under maintenance.");
$jfeta = mysql_fetch_assoc($jsqla);

$id = $jfeta['id'];
$_SESSION['id'] = $id;
Nanga
  • 73
  • 2
  • 7
  • 4
    The syntax highlighting already tells you that your variables in the query are not evaluated: `'".$pass."'`. Also, [please read this](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). And please do not ask questions "my code is not working". Always include what exactly is not working with what kind of error. – Bowdzone Jan 15 '15 at 07:59
  • @Bowdzone maybe his code is really not working - it stays home and watch TV ;-) – violator667 Jan 15 '15 at 08:17

3 Answers3

3

mysql is deprecated. Use mysqli or PDO instead.

nevertheless... update your query.

For better overview and debugging store your sql query first in a variable:

$sql = "select id, user_name, user_type from users where pw='".$pass."' and email='".$email."'";

Now use this code:

(http://php.net/manual/en/function.mysql-fetch-assoc.php)

$result = mysql_query($sql);


if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

$row = mysql_fetch_assoc($result);

$id = $row["id"];

$_SESSION['id'] = $id;

But again ... use mysqli or PDO - mysql is deprecated!

Warning

This extension is deprecated as of PHP 5.5.0, and will be removed in the future.

goldlife
  • 1,949
  • 3
  • 29
  • 48
2

First check whether the session variable is set or not using the below code.

if(isset($_SESSION['id'])) {
  echo $_SESSION['id'];
} else { 
  echo "error."; 
}
Amare
  • 685
  • 2
  • 8
  • 22
1

Did you used session_start to start a session?

<?php
session_start();
?>

After this

$id = $jfeta['id'];

should work:

<?php
    $jsqla = mysql_query("select id, user_name, user_type from users where pw='".$pass."' and email='".$email."'") or die("Website under maintenance.");
    $jfeta = mysql_fetch_assoc($jsqla);

    session_start();
    $id = $jfeta['id'];
    $_SESSION['id'] = $id;
?>

your Selection could be the Problem too:

$jsqla = mysql_query("select id, user_name, user_type from users where pw='$pass' and email='$email'") or die("Website under maintenance.");

could work better with this:

$jsqla = mysql_query("select id, user_name, user_type from users where pw='".$pass."' and email='".$email."'") or die("Website under maintenance.");

The message "Undefined index" means that the one value you use isn't set. you can prevent this by example:

if(isset($jfeta['id']))
{
    //do thing
}
Maximilian Ast
  • 3,369
  • 12
  • 36
  • 47