title: Retrieve Results from DB with Foreach
body: <p>I thought that this would be an easier thing to do, but I'm trying to get into better coding practices and I keep hearing that while is not a good way to loop results, so now I'm trying to switch and I thought I had it down, but no dice. My original code would have been</p>
  
  <pre><code>public function GetSiteName() {
  $query = &lt;&lt;&lt;SQL
  SELECT site_name
  FROM site_details
  SQL;
  
  $resource = $this-&gt;db-&gt;prepare( $query );
  $resource-&gt;execute();
  while($row = $resource-&gt;fetch(PDO::FETCH_ASSOC)){
  echo $row['site_name'];
      }
  }
  </code></pre>
  
  <p>So I've tried changing it to a foreach loop and I've gotten about a million different ways to do it using mysql extensions. (I'm fairly positive 99% of people would say it's better to use a while loop than go to mysql and use a deprecated function)
  So instead what I'm trying isn't working</p>
  
  <pre><code>public function GetSiteName(){
  $query = &lt;&lt;&lt;SQL
  SELECT site_name
  FROM site_details
  SQL;
  
  $resource = $this-&gt;db-&gt;prepare( $query );
  $resource-&gt;execute();
  $result = $resource-&gt;fetch(PDO::FETCH_ASSOC);
  foreach($result as $detail){
  echo $detail-&gt;site_name;
      }
  }
  </code></pre>
  
  <p>I'm not sure what I'm doing wrong on here, the first one works just fine, but the second one gives me:</p>
  
  <pre><code>Notice: Trying to get property of non-object in C:\xampp\htdocs\functions.d\db.class.php on line 37
  </code></pre>
  
  <p>However if I try running <code>print_r($result);</code> I get</p>
  
  <pre><code>Array ( [site_name] =&gt; Doxramos ) 
  </code></pre>
  
  <p>I think that's about as many details I can put, but I feel like I'm doing everything correct, but the Notice doesn't lie. I'm just not sure how it can say that on line 37 is trying to get a non object when I'm obviously pulling an array.</p>