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?

  • 1
    Do you have session_start(); ?? – Steve Apr 15 '14 at 15:14
  • You're using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) & should use a [modern one](http://php.net/manual/en/mysqlinfo.api.choosing.php). You're *probably* **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. You don't seem to be [hashing passwords](http://php.net/manual/en/faq.passwords.php) and need to [take better care](https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet) of them. – Quentin Apr 15 '14 at 15:16
  • ...not to mention probable plain text password storage. – Funk Forty Niner Apr 15 '14 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 – user3521673 Apr 15 '14 at 15:20

2 Answers2

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'];
John Conde
  • 217,595
  • 99
  • 455
  • 496
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

Krimson
  • 7,386
  • 11
  • 60
  • 97