Variable scope

I am new and I have this book I am reading. One of the examples is to connect to a database and retrieve results. There are three pages.

Page 1

<?php try { $pdo = new PDO('mysql:host=localhost;dbname=lphp', 'root', ''); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec('SET NAMES "utf8"'); } catch (PDOException $e) { $error = 'Unable to connect to the database server.'; include 'error.html.php'; exit(); } try { $sql = 'SELECT joketext FROM joke'; $result = $pdo->query($sql); } catch (PDOException $e) { $error = 'Error fetching jokes: ' . $e->getMessage(); include 'error.html.php'; exit(); } while ($row = $result->fetch()) { $jokes[] = $row['joketext']; } include 'jokes.html.php'; ?>


Then there is the index file which is just a page to start things so it just include the above file. Then there are two other pages one to display errors:

Script Output

<?php echo $error; ?>


and one to display the results


<?php foreach ($jokes as $joke) { echo htmlspecialchars($joke, ENT_QUOTES, 'UTF-8'); } ?> [/php]

I get a variable undefined error although it should work in my opinion. I want to know why is the variable $jokes which is actually an array undefined in this context?

If your query isn’t returning any results it could be undefined. You should create the array before your while loop:

$jokes = array();
while ($row = $result->fetch()) {
$jokes[] = $row[‘joketext’];

Thank you that solved it

Sponsor our Newsletter | Privacy Policy | Terms of Service