Undefined variable

If you do a foreach and you have something like: foreach($variable1 as $variable2) then isn’t variable2 being defined in the argument?

I have the following handler
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’;
foreach ($results as $row) {
$authors[] = array(‘id’ => $row[‘id’], ‘name’ => $row[‘name’]);
include ‘authors.html.php’;

and then the page that should display the content
[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


On the page that should display the content 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 would like to understand this so any help would really be appreciated.

If these are separate files where one isn’t included in the other you’d need to use a session variable as the second file wouldn’t know anything about variables declared in the first.

If the second piece of code was a function within the first and you were trying to treat $authors as a global variable you’d need to declare it as global within that function:


<?php global $authors; foreach ($authors as $author){ ... ... } [/php]
Sponsor our Newsletter | Privacy Policy | Terms of Service