phppdo

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

Solution

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

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