PHP MySQL登录后在profile.php显示用户名字而非用户名的问题
Hey there! As someone who’s helped folks make the jump from static design to backend PHP, I totally get this small but tricky adjustment. Let’s walk through exactly where you need to tweak your code:
Step 1: Ensure the first name is stored in the session (login script)
First, head to your login processing file (usually something like login.php). This is where you validate user credentials and save their info to the session.
You probably have a line like this after querying the database:
$_SESSION['username'] = $row['username'];
Add a line right next to it to store the first name from your database:
$_SESSION['firstname'] = $row['firstname'];
Important: Double-check your database query includes the firstname column! Your SELECT statement should look something like:
SELECT username, firstname, password FROM users WHERE email = ?
If you don’t include firstname here, $row['firstname'] will be empty and won’t save to the session.
Step 2: Update the welcome message in profile.php
Now open profile.php and find the line that outputs the welcome text. It’ll likely look like one of these:
echo 'Welcome "' . $_SESSION['username'] . '"'; // Or using double quotes: echo "Welcome \"{$_SESSION['username']}\"";
Simply replace $_SESSION['username'] with $_SESSION['firstname']:
echo 'Welcome "' . $_SESSION['firstname'] . '"'; // Or the double quote version: echo "Welcome \"{$_SESSION['firstname']}\"";
Quick Troubleshooting Tips
If it still doesn’t work, check these two things:
- Does your
usersdatabase table have afirstnamecolumn, and is there data filled in for your test user? - Did you add
session_start();at the very top of bothlogin.phpandprofile.php? Without this, session variables won’t be accessible across pages.
That’s all it takes! This should swap the username for the first name in your welcome message immediately.
内容的提问来源于stack exchange,提问作者Tiger Digital

