Jump to content
Larry Ullman's Book Forums
spamu

How To Display A Username After Successful Login?

Recommended Posts

Hi everyone,

 

I am a newbie here. I was wondering if someone could help me in how to display the username after successful login. I want to display it beside the <h1>Welcome</h1> which is in the index.php file. 

 

Lets say the username is Harry. After logging in, I would like to display Welcome Harry.

 

I have googled it a bit, and I found that we have to set the username where the session has been started. But I am not sure how to do it here.

 

Please help!

 

Thank you.

 

 

Share this post


Link to post
Share on other sites

Just as a heads-up, the book doesn't assume basic familiarity with PHP and MySQL. If you aren't familiar with sessions, I do worry you're going to be in trouble later in the book, which gets pretty advanced. If you find yourself struggling too much, I'd recommend going back and learning the basics.

 

But, yes, this is a sessions situation. You'd store the username in the session upon login and then display it within the context of the page if it exists. Check out the PHP manual's section on sessions if you're unclear on the specific code. 

Share this post


Link to post
Share on other sites

The following is code that I have used to get the username or whatever wording you desire from the database and then display it. I have used "Hello". The session is started in the config.inc.php file. The user's information is stored in the database once it has been sent there from a form that you have set up on your website.

 

<?php

$q = "SELECT id, username FROM users WHERE id={$_SESSION['user_id']}";

$r = mysqli_query($connect, $q);

if (mysqli_num_rows($r) > 0) {

while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) {
    
// Display the username and heading
        
 echo "<h2>Hello $row[1]! <br /></p>

 Your Notices should appear in alphabetical order below. <br /></p>
 
 Click on the notice that you wish to edit.</h2></p>";
}
}
?>

Share this post


Link to post
Share on other sites

I assume that works for you? However, if you already store the user's ID in the session somehow perhaps the code that does that would also store the username in the session so you don't need another query?

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...