Reputation: 662
I am making a profile page for a user on my site, where the person can change his/her information. I should be possible to change, name, lastname, username, code etc. But I have started with the username.
When a person log in, I store the username in session:
index.php
<?php
if( !isset( $_SESSION['username'])) include('resources/auth/login.php');
else exit( header('Location: home.php') );
if( !isset( $_SESSION ) ) session_start();
// Logout Session
if( isset( $_GET['todo'] ) && $_GET['todo'] == 'logout'){
session_unset();
session_destroy();
//echo 'You have been logged out!';
}
?>
I have made a test on
profile.php:
<?php
if( !isset( $_SESSION ) ) session_start();
?>
<?php //echo $_SESSION['username'];?>
and this calls my username
But If I want to call the firstname from mysql database, that belongs to that username, should I use the session[username]
for that? I startet to make a SQL query for it instead:
<?php
$stmt = $mysqli->prepare("SELECT firstname FROM login");
$stmt->execute();
$fname = null;
$stmt->bind_result($fname);
while($stmt->fetch()) {
echo $fname;
}
$stmt->close();
$mysqli->close();
?>
This works, but calls all the firstnames in the database. So I tried to set the u_id, which is the PK in db = to stored session variable:
$stmt = $mysqli->prepare("SELECT firstname FROM login WHERE u_id=$username");
and
$stmt = $mysqli->prepare("SELECT firstname FROM loginWHERE u_id = '.$_SESSION[username]'";
But here I get an error: Undefined variable: username in profile.php
Can anybody see why that is?
Upvotes: 1
Views: 3339
Reputation:
if i understand you well,i think this query:
$stmt = $mysqli->prepare("SELECT firstname FROM login WHERE u_id=$username");
should be this:
$stmt = $mysqli->prepare("SELECT firstname FROM login WHERE username ='.$_SESSION[username].'");
//forgive my syntax issues
if you want to retrieve the firstname of a user that is logged, the parameter for the where clause should be the the user's username as that is the only unique way to identify the user, however may i suggest you also set the id of the user in a session too, so that the where parameter now takes the user's unique id. Its a better way of making sure you retrieve information for that particular user, because two users may have the same username, so when your where clause takes that as a parameter, it retrieves two rows from the database, that will definitely cause problems.
Upvotes: 1
Reputation: 108
It is high propable that you didn't start the session. I only know the writing $_SESSION['username'] instead of u_id = ' . $_SESSION[username]'
Upvotes: 1