I am reviewing PHP & MySQL Novice to Ninja and following along with the code sections. I’m stuck with this error, though I believe I followed the code as I should. I’ve checked it over and over and can’t see the cause.
The error messages point to line 10, <?php foreach ($authors as $author): ?> :
[I]Notice: Undefined variable: authors in C:\wamp\www\PHP_MySQL\jokecms\authors\authors.html.php on line 10
Warning: Invalid argument supplied for foreach() in C:\wamp\www\PHP_MySQL\jokecms\authors\authors.html.php on line 10[/I]
The code of that page is:
<!DOCTYPE html>
<html lang="en">
<head><title>Manage Authors</title></head>
<!--p192-193 of Yank book. Linked from authors/index.php-->
<?php include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php'; ?>
<body>
<h1>Manage Authors (p192)</h1>
<p><a href="?add">Add new author</a></p>
<ul>
[COLOR="#FF0000"]<?php foreach ($authors as $author): ?>[/COLOR]
<li>
<form action="" method="post">
<div id="form">
<?php htmlout($author['name']); ?> <!--see helpers.inc.php-->
<input type="hidden" name="id" value="<?php echo $author['id']; ?>">
<input type="submit" name="action" value="Edit">
<input type="submit" name="action" value="Delete">
</div>
</form>
</li>
<?php endforeach; ?>
</ul>
<p><a href="..">Return to JMS home</a></p>
</body>
</html>
No DB output is displayed; only the above notices and the <h1> and <p> content above and below it. The above is an include (authors.html.php) for this index.php page:
<?php
include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php';
// The query to show authors listed in DB
try
{
$result = $pdo->query('SELECT id, name FROM author');
}
catch (PDOException $e)
{
$error = 'Error fetching authors from the database!';
include 'error.html.php';
exit();
}
foreach ($result as $row)
{
$authors[] = array('id' => $row['id'], 'name' => $row['name']);
}
include 'authors.html.php'; // shows authors and Edit/Delete buttons
I can use a couple extra eyes on this!