Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO get information by username

Tags:

php

mysql

pdo

Okay, i'm logged in as "Admin", the admin have information - money, xp. I have the 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 do that information is received by the logged in person?

like image 590
Noyz Avatar asked Jul 04 '26 02:07

Noyz


2 Answers

Just select the specific row (user credentials) using the currently logged in user.

Assuming you're 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
}
like image 108
Kevin Avatar answered Jul 05 '26 17:07

Kevin


Save the logged in user id in a normal variable 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 = ?');
$query->execute([$_SESSION['UserID']]);

foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row) {
    echo 'Name: '. $row['Name'] . '<br>Money: '.$row['Money'] . '<br>XP: '.$row['XP'];
}
like image 29
Luthando Ntsekwa Avatar answered Jul 05 '26 16:07

Luthando Ntsekwa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!