0

I'm playing around with PDO trying to really understand it. I have a small piece of code that selects all from a table, then displays the results on page. This works fine:

$query = $connection->query('select * from stats');

while ($row = $query->fetch()) {

    echo $row['display_name'] . ' - ' . $row['short_name'] . '<br>';

}

This works as expected, returning the following to the page:

Connected to the database.
Magic - mag
Attack - atk
Defence - def

The only code before this is a try...catch connecting to the database (creating a new object $connection) - that's where the 'Connected to the database' line is coming from. If I try the following in a function, I see nothing on page:

function listAllStats() {

    $query = $connection->query('select * from stats');

    while ($row = $query->fetch()) {

        echo 'From my function: ' . $row['display_name']; 

    }

};

listAllStats();

Any ideas what I'm doing wrong?

D. Winning
  • 302
  • 1
  • 13
  • 1
    `$connection` is not defined inside your function. You could pass it as a parameter e.g. `function listAllStats($connection)` – Nick Mar 24 '19 at 12:07
  • @Nick thank you, I figured this out based on the question this was marked as a duplicate of. It would still be nice for newer developers if there weren't so many people that love to mash that downvote button. I come from a JS background, where you can use variables defined in the global scope within a function. – D. Winning Mar 24 '19 at 15:29
  • Not quite sure why the downvote, I don't think this is a poor question. – Nick Mar 24 '19 at 21:36

0 Answers0