user1187135
user1187135

Reputation:

Display only one column of a PDO result set

I am trying to display "name" object, but its not working. I seem to be using foreach wrong.. I print_r for $a and it displays the array. Can someone help.

public function product(){
    $st = $this->db->prepare("select id, name, description, price from deals where quantity > 0 order by id desc");
    $st->execute();
        
    if ($st->rowCount() == 0){
        echo "There are no products to display";
    } else {
        $a = $st->fetch(PDO::FETCH_OBJ)
            
        foreach ($a as $products){
            echo $products->name;
        }
    }
}

Upvotes: 1

Views: 241

Answers (2)

SpacedMonkey
SpacedMonkey

Reputation: 2773

fetch() only returns one row. Your foreach is looping through all the properties of the object returned by fetch(), i.e. the column names.

Upvotes: 0

jeffjenx
jeffjenx

Reputation: 17457

I don't think you need a foreach loop for what you are doing.

while( $products = $st->fetch(PDO::FETCH_OBJ) )
{
    echo $products->name;
}

Upvotes: 2

Related Questions