Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP CRUD Operations with PHP Creating Records Reading Data

Thomas Morling
Thomas Morling
12,754 Points

PDO Statement Object - I can't get challenge 2 to work

<?php function get_podcasts() { include 'connection.php';

//add code here
     $stmt = $db->query('SELECT * FROM podcasts');

return($stmt);

}

get_podcasts() {

// $result = $query -> fetchAll();

foreach( $stmt as $row ) { echo $row['title']; echo $row['website']; } }

index.php
<?php
function get_podcasts() {
    include 'connection.php';

    //add code here
         $stmt = $db->query('SELECT * FROM podcasts');

  return($stmt);

}

get_podcasts() {

// $result = $query -> fetchAll();

foreach( $stmt as $row ) {
    echo $row['title'];
    echo $row['website'];
}
} 

2 Answers

You are pretty close, there are just a few mistakes which are mostly to do with syntax.

Your get_podcasts() function is implemented correctly, but you'll need to call the function outside of it's implementation and assign it's return value to a variable:

$podcasts = get_podcasts();

Also note that in your code you use curly braces( { } ) after you try to call the function, but with functions you only use those when you're implementing a function; not when you are calling it.

Now recall from the problem instructions that get_podcasts() returns a PDOStatement Object, but we need an array of the rows from the podcasts table in order to loop through each podcast. Thus, we will modify the above code snippet as follows:

$podcasts = get_podcasts()->fetchAll();

Now we can loop through $podcasts:

foreach ($podcasts as $podcast) {
    echo $podcast['title'];
    echo $podcast['website'];
}