joshuahornby10
joshuahornby10

Reputation: 4302

Loop a query to return all values

I have a basic MVC set up for my basic website. There is a class which calls (a model) the database and runs a query on it, it also has the view method for accessing the view

<?php
class Products {

    public function view( $file_name, $data = null ) 
    {
        if( is_array($data) ) {
           extract($data);
        }

        include 'application/view/' . $file_name;
    }

    public function getProducts () {
        $stmt = Database::get()->query ('SELECT * FROM retrofootball_products WHERE id>4');
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result;

    }
}

It then passes this to the view and displays this

<?php require 'application/view/template/header.html'; ?>

<div class="product">


<div class="eight columns">

</div>    

<div class="eight columns">
<?php echo "$productname    ";echo  "| Price £$price";?>

</div>

</div>

I want to display all the fields in a list like the first one does Manchester City 1999 Playoff Winning Shirt | Price £40 But my view can only access the column names just as $productname

Is there a way to loop through my query to display all the product? I have tried returning an array but then the view won't let me declare this. It only lets me pass through column names. I have added the structure of my small website in a gist:

https://gist.github.com/d7a21ceee5e36b4f6198

Upvotes: 1

Views: 174

Answers (1)

ThiefMaster
ThiefMaster

Reputation: 318488

public function getProducts () {
    $stmt = Database::get()->query ('SELECT * FROM retrofootball_products WHERE id>4');
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

This will give you an array containing all result rows. In your template you can then use a foreach loop to iterate over the rows.

<?php require 'application/view/template/header.html'; ?>
<?php foreach($products as $product) { ?>
  <div class="product">
    <div class="eight columns"></div>    
    <div class="eight columns">
      <?php echo htmlspecialchars($product['name']) .' | Price £' . $product['price']; ?>
    </div>
  </div>
<?php } ?>

Upvotes: 1

Related Questions