Skittles
Skittles

Reputation: 11

Write an ID into session as a variable

I need to insert an ID into session for later use. Table contains ID, username and password. To get the ID im using:

$sql = "SELECT id FROM members WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

And trying to store it into session:

$_SESSION["id"] = $result;

When im trying to insert $_SESSION[id] into a table I get the value of 0 (which is the default value I made).

Kinda new on PHP, any help would be appriciated :)

Upvotes: 1

Views: 205

Answers (3)

s3v3n
s3v3n

Reputation: 8446

mysql_query() returns a resource on success, or FALSE on error. You need to fetch the rows from that result:

$result = mysql_query("SELECT id, name FROM mytable") or die(mysql_error());
$row = mysql_fetch_array($result);
if($row){ // check that there was really selected at least one row
    $_SESSION['id'] = $row['id'];
}

Upvotes: 0

Amirshk
Amirshk

Reputation: 8258

Attempting to print $result won't allow access to information in the resource.

You need to use a function to access the resource returned:

$row = mysql_fetch_assoc($result)
$id = $row['id'];

The proper way to handle result would be to first check it has any value at all, i.e.:

if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);
}

Upvotes: 0

getaway
getaway

Reputation: 8990

you need fetch the value aswell:

$result=mysql_query($sql);
$fetch =mysql_fetch_array($result);
$_SESSION["id"] = $fetch["ID"];

Upvotes: 1

Related Questions