0

I'm doing a project where I'm supposed to create a website that people can register and log in. I'm trying to do that thing where it will say in the corner "Logged in as ..."

This is part of the code that assigns the variable name to the name value in the database when the user logs in.

    $first = mysql_query("SELECT FirstName FROM students WHERE studentID = '$user' AND password = '$pass'");
    $firstname = mysql_fetch_array($first);
    $_SESSION['name'] = $firstname;

And this is the code on the website that displays the name

<?php 
if(isset($_SESSION['name']))
{
echo '<li class="disabled"><a href="#" disabled>Signed in as ' . $_SESSION['name'] . '</a></li>';
} 
?>

But when the website is actually ran the space is left blank. I know the variable is set because I replaced $_SESSION['name'] with some random string and it echo'd it fine. I also ran the SQL query and it gave me back the name. What am I missing from my code?

4
  • 1
    Do you have session_start(); ?? Commented Apr 15, 2014 at 15:14
  • You're using an obsolete database API & should use a modern one. You're probably vulnerable to SQL injection attacks that a modern API would make it easier to defend yourself from. You don't seem to be hashing passwords and need to take better care of them. Commented Apr 15, 2014 at 15:16
  • ...not to mention probable plain text password storage. Commented Apr 15, 2014 at 15:19
  • Yes I have session_start();, and Quentin, I have no intention of actually creating a user base because this is just a little project for school, but thank you for telling me and I'll take your advice if I want to start something serious Commented Apr 15, 2014 at 15:20

2 Answers 2

2

mysql_fetch_array(), as the name implies, returns an array of values. Not just the one column you have selected.

$row = mysql_fetch_array($first);
$_SESSION['name'] = $row['FirstName'];
Sign up to request clarification or add additional context in comments.

Comments

0

Try replacing

mysql_fetch_array($first);

with

mysql_fetch_array($first)['FirstName'];

Also avoid using mysql_* function. They have been depricated. Use mysqli_* instead or PDO

2 Comments

This ['FirstName '] will result in not showing the row, since there's a space. Change to ['FirstName']
opps, sorry typo, and I guess John beat me to first ans

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.