How do I match the logged in user to his/her member name from the DB and use echo to display it on the page they are visiting?

Hi, new to the forum! I have a simple PHP question that I couldn’t seem to find a sufficient answer for by searching. I have a small MySQLi DB and want to retrieve something from “members”, based on which user is currently logged on. Something like “Hi member!” but replacing “member” with the matching logged in user’s name (member_name) from the DB. I know about “select” and all, but I just can’t figure it out. Any help would be most appreciated!

Please go easy on me, I’m a total PHP noob. :smile:

Generally, when a user logs in you would set a session variable containing the data you want to display in the app and then just echo that variable where you want it displayed.

This only applies to something you would want to persistently display such as the persons name. Other data would be queried as needed.

1 Like

Okay thanks! So I added this to my login code:

$_SESSION[‘member_name’] = $username;

How do I echo it? I tried: <?php echo $username; ?>, <?php echo $member_name; ?>, and <?php echo "$member_name;" ?> and none is working. :frowning:

Where are these variables magically coming from? If your using a Database the values would come from the query result. If you set the session properly you would echo the session.

$_SESSION['member_name'] = $row['username'];

echo "Hello {$_SESSION['member_name']}";

It’s not working. :frowning: Here’s the snippet from my account creation code:

  if (count($errors) == 0) {
      $password = password_hash($password, PASSWORD_BCRYPT);
  	
  	$query = "INSERT INTO members (member_name, member_email, member_password) 
  			  VALUES('$username', '$email', '$password')";
  	mysqli_query($db, $query);
  	$_SESSION['member_name'] = $row['member_name'];
  	header('location: thanks.html');
  }

I said login, not account creation.

Also, NEVER EVER put variables in your query. You need to use Prepared Statements.

1 Like

Speaking of variables and prepared statements, I changed the mentioned code to:

// Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
      $password = password_hash($password, PASSWORD_BCRYPT);

      $sql = "INSERT INTO members (name, password, email) VALUES (?, ?, ?);
	if($stmt = mysqli_prepare($db, $sql)){
    // Bind variables to the prepared statement as parameters
      mysqlstmt_bind_param($stmt, "sss", $member_name, $member_passwored, $member_email);
	$username = "member_name";
	$password = "member_password";
	$email = "member_email";

      mysqli_stmt_execute($stmt);

  	// mysqli_query($db, $query);
  	// $_SESSION['member_name'] = $row['members'];
  	header('location: thanks.html');
  }

And now I broke the script. :frowning: Help please!

Nobody is going to know what that means.

I would highly recommend you use PDO instead of mysqli.

Yes, I tried to use prepared statements in the code I showed, and it doesn’t work, this is the code snippet in reference:

if (count($errors) == 0) {
$password = password_hash($password, PASSWORD_BCRYPT);

  $sql = "INSERT INTO members (name, password, email) VALUES (?, ?, ?);
if($stmt = mysqli_prepare($db, $sql)){
// Bind variables to the prepared statement as parameters
  mysqlstmt_bind_param($stmt, "sss", $member_name, $member_password, $member_email);
$username = "member_name";
$password = "member_password";
$email = "member_email";

  mysqli_stmt_execute($stmt);

// mysqli_query($db, $query);
// $_SESSION['member_name'] = $row['members'];
header('location: thanks.html');

}

If this is not correct, then how do I fix it? It simply produces a blank screen.

I would suggest you take a look at the countless scripts and tutorials that are out there and actually learn about what you are trying to do. It’s pretty clear you are just throwing stuff out hoping it sticks to the wall without understanding what you are doing.

Your OP says you want to " retrieve something from “members", based on which user is currently logged on." yet you keep posting code related to registering a user. You arent “retrieving” anything.

1 Like

My bad, I am working on two things at once. Anyway, I got it working with PDO! Thanks for your help!! :slight_smile:

Okay I put this right after user login authentication:

$_SESSION['node'] = $row['member_name'];

As member_name is the row that holds members names. And then this on the logged in member’s home page:

<?php echo "{$_SESSION['node']}"; ?>

But it displays nothing. :frowning:

I need a simple way of echoing the logged in user’s name on a particular PHP page in my site. In my login routine I added this right after the user is authenticated (the username is stored in “member_name” in my DB:

$_SESSION["node"] = $user[0]["username"];

I also tried many variations such as:

$_SESSION["node"] = $member_name;

etc. Then in my main logged in page, I put this:

<?php echo ($_SESSION['node']);?>

It doesn’t work. lol Am I even close here? And is there an easier way? Thanks!

What should that mean? No one here sits in front of your computer. You can output variables at any point with var_dump(), right after the assignment and where you want to show something. There’s a null value or not what you expected? Just use the next upper key of the array or the complete array with var_dump().

We’d need to see the code in context to have a chance of trying to help figure out what’s wrong. There is nothing wrong with any of the lines of code you posted, in isolation, so the key will be how they interact with the rest of the code.

Is that right at the start of your PHP code? Before you call session_start()?

I got a blank screen. I did fix that, but it now simply displays nothing (it shows the page and other content, but echos nothing).

Okay thanks!

Okay here is the complete login function:

if (! empty($_POST["login"])) {
    $isAuthenticated = false;
    
    $username = $_POST["member_name"];
    $password = $_POST["member_password"];
    
    $user = $auth->getMemberByUsername($username);
    if (password_verify($password, $user[0]["member_password"])) {
        $isAuthenticated = true;
    }
    
    if ($isAuthenticated) {
        $_SESSION["member_id"] = $user[0]["member_id"];
        
        // Set Auth Cookies if 'Remember Me' checked
        if (! empty($_POST["remember"])) {
            setcookie("member_login", $username, $cookie_expiration_time);
            
            $random_password = $util->getToken(16);
            setcookie("random_password", $random_password, $cookie_expiration_time);
            
            $random_selector = $util->getToken(32);
            setcookie("random_selector", $random_selector, $cookie_expiration_time);
            
            $random_password_hash = password_hash($random_password, PASSWORD_DEFAULT);
            $random_selector_hash = password_hash($random_selector, PASSWORD_DEFAULT);
            
            $expiry_date = date("Y-m-d H:i:s", $cookie_expiration_time);
            
            // mark existing token as expired
            $userToken = $auth->getTokenByUsername($username, 0);
            if (! empty($userToken[0]["id"])) {
                $auth->markAsExpired($userToken[0]["id"]);
            }
            // Insert new token
            $auth->insertToken($username, $random_password_hash, $random_selector_hash, $expiry_date);            
        } else {
            $util->clearAuthCookie();
        }
	$_SESSION['node'] = $row['member_name'];
        $util->redirect("main.php");
    } else if (empty($username)) {
	  $message = "<br><span style='width:92%;margin:0px auto;padding: 10px;border: 1px solid #a94442; color: #a94442; background: #f2dede; border-radius: 5px; text-align: left;'>Username can't be empty!</span>";
    } else if (empty($password)) {
	  $message = "<br><span style='width:92%;margin:0px auto;padding: 10px;border: 1px solid #a94442; color: #a94442; background: #f2dede; border-radius: 5px; text-align: left;'>Password can't be empty!</span>";
    } else {    
        $message = "<br><span style='width:92%;margin:0px auto;padding: 10px;border: 1px solid #a94442; color: #a94442; background: #f2dede; border-radius: 5px; text-align: left;'>Invalid Username/Password!</span>";
    }
}

And the echo in main.php:


<span style="color:white;font-size:20px;">Welcome <span style="color:orange;">
<?php echo "{$_SESSION['node']}"; ?></span>!</span>

Thanks!

$_SESSION['node'] = $row['member_name'];

There is no other reference to $row in your code - you don’t read it from anywhere, so it’s no surprise that this doesn’t do anything.

Does your code set the member_id session variable correctly, and can you display that (even just for debugging purposes) in your main.php code?

I didn’t notice this before. Perhaps that is the cause of some confusion - member_name is the column that holds members names, not the row.

1 Like

Post the getMemberByUsername method. As I mentioned before, something is funky with the zero array you are using.

1 Like

Here it is:

function getMemberByUsername($username) {
        $db_handle = new DBController();
        $query = "Select * from members where member_name = ?";
        $result = $db_handle->runQuery($query, 's', array($username));
        return $result;
}