Undefined variable

I have a handler page index.php with the following code
[php]<?php
include_once ‘db_connect.inc.php’;

try {
$result = $pdo->query(‘SELECT id, name from author’);
}
catch (PDOException $e) {
$error = ‘Error fetching authors from database’;
include ‘error,html.php’;
exit();
}
foreach ($results as $row) {
$authors[] = array(‘id’ => $row[‘id’], ‘name’ => $row[‘name’]);
}
include ‘authors.html.php’;
?>[/php]

Then I have a page to display the results
[php]<?php include_once $_SERVER[‘DOCUMENT_ROOT’] .
‘Netbeans/PHP Power/includes/helpers.inc.php’; ?>

Manage Authors

Manage Authors

Add new author

    <?php foreach ($authors as $author): ?>
  • <?php htmlout($author['name']); ?>
  • <?php endforeach; ?>

Return to JMS home

[/php]

When I look at the page I get the following error:

Notice: Undefined variable: authors in C:\wamp\www\Netbeans\PHP Power\admin\authors\authors.html.php on line 13 (which is the file above on line 13)

I have tried but cannot figure this out. Why is the variable authors undefined. Is it not defined in the handler script and passed to the html page?

I don’t see where $results is defined either? I think you can avoid the loop and just use fetchAll for example:

[php]

<?php include_once 'db_connect.inc.php'; $authors = array(); // define $authors try { $result = $pdo->query('SELECT id, name from author'); $authors = $result->fetchAll(PDO::FETCH_ASSOC); // fetch authors array } catch (PDOException $e) { $error = 'Error fetching authors from database'; include 'error,html.php'; exit(); } include 'authors.html.php'; ?>

[/php]

I did what you told me to and no errors but also no results are showing and I know for a fact there are authors in the database

Just debug. Do a var_dump and see what it shows.

[php]
try {
$result = $pdo->query(‘SELECT id, name from author’);
$authors = $result->fetchAll(PDO::FETCH_ASSOC); // fetch authors array
var_dump($authors);
}
[/php]

in this code here:
[php]<?php
include_once ‘db_connect.inc.php’;

try {
$result = $pdo->query(‘SELECT id, name from author’);
}
catch (PDOException $e) {
$error = ‘Error fetching authors from database’;
include ‘error,html.php’;
exit();
}
foreach ($results as $row) {
$authors[] = array(‘id’ => $row[‘id’], ‘name’ => $row[‘name’]);
}
include ‘authors.html.php’;
?>[/php]

you are trying to reference a variable that does not exist, thus the $authors array will not get populated.
$results & $result are not the same thing…

[php]$result = $pdo->query(‘SELECT id, name from author’);
foreach ($results as $row) {
$authors[] = array(‘id’ => $row[‘id’], ‘name’ => $row[‘name’]);
}
[/php]

:wink:

Sponsor our Newsletter | Privacy Policy | Terms of Service