On login:
$result = mysql_query("SELECT `id`, `username`, `email` FROM `users`
WHERE `username` = '$username'
AN开发者_StackOverflow社区D `password` = '$passwd'");
$userdata = array('id','username','email');
$_SESSION['user'] = mysql_result($result, 0, $userdata);
And when I want to print the users username:
echo $_SESSION['user']['username']
it only prints the first letter :/
What's wrong?
Debug your variables at each stage by using var_dump() to determine where the problem lies. Also, using mysql_result in that fashion is needless, I'd recommend using mysql_fetch_assoc() as it will do the same thing with less effort.
try this
$_SESSION['user']['id'] = mysql_result($result, 0, 'id');
$_SESSION['user']['username'] = mysql_result($result, 0, 'username');
$_SESSION['user']['email'] = mysql_result($result, 0, 'email');
also make sure the database itself doesn't contain only first letter initially.
I think you probably want to be using mysql_fetch_assoc() instead of mysql_result(). mysql_result()
only gives you a single cell value from your result set, so when you assign $_SESSION['user'] = mysql_result($result,0,$userdata);
, you are only getting the first cell value of the result row. Accessing it by an associative key (ie. $_SESSION['user']['username']
) isn't possible, since it's not an array.
If you use mysql_fetch_assoc()
, you'll have a key/value pair of your column names and values to work with:
$result = mysql_query("SELECT `id`, `username`, `email` FROM `users`
WHERE `username` = '".mysql_real_escape_string($username)."'
AND `password` = '".mysql_real_escape_string($passwd)."'");
$_SESSION['user'] = mysql_fetch_assoc($result);
As a side benefit, mysql_fetch_assoc()
is much faster than mysql_result()
.
Note: I also put a mysql_real_escape_string() in there, as you must be sure to escape your query data somehow, unless you are sure it's safe.
精彩评论