Notice: Undefined index: selected

I’m currently reading through “Sitepoint Build Your Own Database Driven Website Using PHP and MySQL” (Jul 2009).

I’m at “chapter7/admin/jokes/form.html.php” where I get the following:

Here’s the code:

<?php include_once $_SERVER['DOCUMENT_ROOT'] .
'/includes/'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<html xmlns="" xml:lang="en" lang="en">
<title><?php htmlout($pagetitle); ?></title>
<meta http-equiv="content-type"
content="text/html; charset=utf-8"/>
<style type="text/css">
textarea {
display: block;
width: 100%;
<h1><?php htmlout($pagetitle); ?></h1>
<form action="?<?php htmlout($action); ?>" method="post">
<label for="text">Type your joke here:</label>
<textarea id="text" name="text" rows="3" cols="40"><?php
htmlout($text); ?></textarea>
<label for="author">Author:</label>
<select name="author" id="author">
<option value="">Select one</option>
<?php foreach ($authors as $author): ?>
<option value="<?php htmlout($author['id']); ?>"<?php
if ($author['id'] == $authorid)
echo ' selected="selected"';
?>><?php htmlout($author['name']); ?></option>
<?php endforeach; ?>
<?php foreach ($categories as $category): ?>
<div><label for="category<?php htmlout($category['id']);
?>"><input type="checkbox" name="categories[]"
id="category<?php htmlout($category['id']); ?>"
value="<?php htmlout($category['id']); ?>"<?php
if ($category['selected'])
echo ' checked="checked"';
?>/><?php htmlout($category['name']); ?></label></div>
<?php endforeach; ?>
<input type="hidden" name="id" value="<?php
htmlout($id); ?>"/>
<input type="submit" value="<?php htmlout($button); ?>"/>

Anyone know what causes this?

Yes. On line 44 there is a referenced to an undefined index called “selected”

The $category variable seems to have ‘id’, but there doesn’t seem to be any ‘selected’ in the $category variable.

Start tracing it back. Find out what fields the $category variable contains, then trace back further to the $categories variable to check whether it’s being populated with the data that you expect it to have.