Fetching and displaying Data for Each Registered User in PHP using PDO [duplicate]

…衆ロ難τιáo~ 提交于 2020-05-09 17:28:26

问题


I have been trying to fetch data from the database and display each user's data on their dashboard, but what is giving me is the whole data in the database. I have tried many fetch data functions but some will give me error. I had check round the web and here to see if I can get something close to mine challenge but I have not been able to get any helpful one.

This is my code

$sql="SELECT * from users";
$query = $pdo -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);

$cnt=1;
if($query->rowCount() > 1)
{
    foreach($results as $row)
    {                



This is the database structure

This is the user dashboard. It should return the data according to the username. Any method of fetch I used will return error.


回答1:


Have your SQL statement query for the columns that you wish your obtain (not sure where your Date data is coming from though).

$statement = $pdo->prepare('SELECT id, username, email FROM users');
$statement->execute();
while($row = $statement->fetch(\PDO::FETCH_ASSOC)) {
    $id = $row['id'];
    $username = $row['username'];
    $email = $row['email'];
    // Validate and do something with this data
}

Also, make sure your syntax is correct. As your example code is not.

Edit:

As mentioned; if you only want data for a specific user, you need to add filtering clauses to your SQL statement.

For example:

$statement = $pdo->prepare('SELECT id, username, email FROM users WHERE id = :id');
$statement->bindValue('id', $someUserId);


来源:https://stackoverflow.com/questions/61280469/fetching-and-displaying-data-for-each-registered-user-in-php-using-pdo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!