2
votes

I'm new in php, I'm trying to display stdClass Object data via foreach loop inside table. But it's not working.

include("../config.php");
$get_data = $conn->query("SELECT * FROM `prd_rgistration`");
$prd_data = $get_data->fetchObject();
print_r($prd_data);

Data Print

stdClass Object
(
    [id] => 24
    [password_db] => kignkgsnis
    [country_db] => United States
    [porder_db] => 56313241654321324
    [email_db] => [email protected]
)

Foreach Loop

foreach($prd_data as $eprd_data){
    echo $eprd_data->id;
}

it's giving this error

Trying to get property of non-object

kindly tell me how i can display data. What thing i'm doing wrong.

4
you fetch only ONE Object. So you can't loop over it. - Andre
USe $get_data->fetchAll(PDO::FETCH_OBJ); then use foreach loop - Saty
oh i see now it's working fine - Muhammad Hamza Nisar

4 Answers

3
votes

You're only getting one object, not an array, so wrap the while loop around fetch

while ($prd_data = $get_data->fetchObject())
  echo $prd_data->id;
2
votes
  1. Add this line in your config.php

    $conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
    
  2. Change your code to

    $get_data = $conn->query("SELECT * FROM `prd_rgistration`");
    foreach($get_data as $prd_data){
        echo $prd_data->id;
    }
    
1
votes

There are two way to do it:-

1.bit modification in your code:-

loop through the results of the query :-

while ($prd_data = $get_data->fetchObject()) {
    echo $prd_data->id;
}

2.Use $prd_data = $get_data->fetchAll(PDO::FETCH_OBJ); and then foreach as you used.

foreach($prd_data as $eprd_data){
    echo $eprd_data->id;
}

Note:- According to me you are interested in fetching all the records,So go for the second one.Thanks

One other way is also suggested by @Your common Sense

0
votes

You need to loop through the results of the query :

while ($prd_data = $get_data->fetchObject()) {
    echo $prd_data->id;
}

Instead of

$prd_data = $get_data->fetchObject();