PHP PDO GET USERNAME INFORMATION
Ok, I am logged in as "Administrator", the administrator has information - money, xp. I have some code:
$query = dbConnect()->prepare("SELECT * FROM players");
$query->execute();
foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo 'Name: '. $row['Name'] . '<br>Money: '.$row['Money'] . '<br>XP: '.$row['XP'];
}
And I have 2 users in mysql. How to make this information personally obtained?
source to share
Store the registered user id in a regular or SESSION variable and use it in your where clause
//so first we save the logged-in user id when the user logs in
$_SESSION['UserID'] = //loggedin user id;
//we then use the user id we save in a where clause to get that specific user
$query = dbConnect()->prepare('SELECT * FROM players WHERE playerID = "'.$_SESSION['UserID'].'"');
$query->execute();
foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo 'Name: '. $row['Name'] . '<br>Money: '.$row['Money'] . '<br>XP: '.$row['XP'];
}
source to share
Just select a specific string (user credentials) using the current user.
Assuming you are using sessions:
session_start();
$username = $_SESSION['username'];
$connection = dbConnect();
$query = $connection->prepare('SELECT * FROM players WHERE username = ?');
$query->execute(array($username));
$result = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($result)) {
// echo credentials
// echo $result['Money']; // etc
}
Or with ->bindValue
with your named placeholder:
session_start();
$username = $_SESSION['username'];
$connection = dbConnect();
$query = $connection->prepare('SELECT * FROM players WHERE username = :username');
$query->bindValue(':username', $username);
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
if(!empty($result)) {
// echo credentials
// echo $result['username']; // etc
}
source to share
Use bindValue()
to bind value :sessionID
to value $_SESSION['UserID']
or else your UserID is stored. This will make it easier to create queries, and you can loop through all the results of your query using a while loop.
$DBO = dbConnect();
$query = $DBO->prepare("SELECT * FROM players WHERE playerID=:sessionID");
$query->bindValue(':sessionID', $_SESSION['UserID'], PDO::PARAM_STR);
$query->execute();
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $query->fetch()) {
//$results[] = $row;
echo 'Name: ' . $row['Name'] . '<br>Money: '. $row['Money'] . '<br>XP: ' . $row['XP'];
}
source to share