简体   繁体   中英

PHP PDO GET INFORMATION BY USERNAME

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?

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
}

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 = "'.$_SESSION['UserID'].'"');
$query->execute();

foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row) {
    echo 'Name: '. $row['Name'] . '<br>Money: '.$row['Money'] . '<br>XP: '.$row['XP'];
}

You can set a session variable with the user's ID $_SESSION['id'] = 'user1'

Then you can frame your SQL statement like this:

SELECT * FROM players WHERE userid = ?

Use bindValue() to bind the value of :sessionID to the value of $_SESSION['UserID'] or however your UserID is stored. It will make creating your queries a little easier, and you can iterate over all of the results from your query with 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'];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM