Write an ID into session as a variable
I need 开发者_如何学Cto 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 :)
you need fetch the value aswell:
$result=mysql_query($sql);
$fetch =mysql_fetch_array($result);
$_SESSION["id"] = $fetch["ID"];
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);
}
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'];
}
精彩评论