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?

+3


source to share


4 answers


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'];
}

      

+3


source


You can set session variable with user id $_SESSION['id'] = 'user1'

Then you can create an SQL statement like this:



SELECT * FROM players WHERE userid = ?

+2


source


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
}

      

+2


source


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'];
}

      

+1


source







All Articles