Undefined variable error

Hi everyone,

The code in the following file has a link that allows the user to add a category and the code submits to a controller file (code shown at the end of this post):

<?php include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
	<title>Manage Categories</title>
	<meta http-equiv="content-type"
				content="text/html; charset=utf-8"/>
</head>
	<body>
		<h1>Manage Categories</h1>
		<p><a href="?add">Add new category</a></p>
		<ul>
			<?php foreach ($categories as $category): ?>
				<li> 
			  <form action="" method="post">
						<div>
							<?php htmlout($category['category']); ?>
                            
					    <input type="hidden" name="catID" value="<?php
									echo $category['catID']; ?>"/>
							<input type="submit" name="action" value="Edit"/>
							<input type="submit" name="action" value="Delete"/>
						</div>
					</form>
				</li>
			<?php endforeach; ?>
		</ul>
	</body>
</html>

The following template file contains the form where the user can edit the category:

form.html.php

<?php include_once $_SERVER['DOCUMENT_ROOT'] .
		'/includes/helpers.inc.php'; ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
		"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
	<title>
	<?php htmlout($pagetitle); ?>
	</title>
	<meta http-equiv="content-type"
				content="text/html; charset=utf-8"/>
</head>
	<body>
		<h1><?php htmlout($pagetitle); ?></h1>
		<form action="?<?php htmlout($action); ?>" method="post">
			<div>
				<label for="name">Category: <input type="text" name="category"
						id="category" value="<?php htmlout($category); ?>"/></label>
			</div>
			<div>
				<input type="hidden" name="catID" value="<?php
						htmlout($catID); ?>"/>
				<input type="submit" value="<?php htmlout($button); ?>"/>
			</div>
		</form>
	</body>
</html>

When the form is displayed, the following is already displaying in the input field:

<br /> <b>Notice</b>: Undefined variable: category in <b>/Applications/MAMP/htdocs/new_site/admin/catalogue/categories/form.html.php</b> on line <b>18</b><br />

Line 18 (which is in the above template file called) is:

id=“category” value=“<?php htmlout($category); ?>”/></label>

I can easily delete this error that’s in the input field and type in a new category and submit it and it successfully inserts it into the database, but I don’t know why the Notice is there in the first place or how to git rid of it.

Can anyone tell me what might be happening?

Appreciate any help.

Controller file code:

<?php
if ($_SERVER['HTTP_HOST'] != "mysite.com") { 
   define ('__ROOT__', $_SERVER['DOCUMENT_ROOT'] . '/new_site');
} else {
   define ('__ROOT__', $_SERVER['DOCUMENT_ROOT']);
}
include_once(__ROOT__ . "/includes/magicquotes.inc.php");


if (isset($_GET['add']))
{
	$pagetitle = 'New category';
	$action = 'addform';
	$name = '';
	$email = '';
	$catID = '';
	$button = 'Add author';

	include 'form.html.php';
	exit();
}

if (isset($_GET['addform']))
{
	include(__ROOT__ . "/includes/dbAdmin.inc.php");

	$category = mysqli_real_escape_string($link, $_POST['category']);
	$sql = "INSERT INTO categories SET
			category='$category'";
	if (!mysqli_query($link, $sql))
	{
		$error = 'Error adding submitted category.';
		include 'error.html.php';
		exit();
	}

	header('Location: .');
	exit();
}

if (isset($_POST['action']) and $_POST['action'] == 'Edit')
{
	include(__ROOT__ . "/includes/dbAdmin.inc.php");

	$id = mysqli_real_escape_string($link, $_POST['catID']);
	$sql = "SELECT catID, category FROM categories WHERE catID='$id'";
	$result = mysqli_query($link, $sql);
	if (!$result)
	{
		$error = 'Error fetching category details.';
		include 'error.html.php';
		exit();
	}
	$row = mysqli_fetch_array($result);

	$pagetitle = 'Edit category';
	$action = 'editform';
	$category = $row['category'];
	$catID = $row['catID'];
	$button = 'Update category';

	include 'form.html.php';
	exit();
}

if (isset($_GET['editform']))
{
	include(__ROOT__ . "/includes/dbAdmin.inc.php");

	$catID = mysqli_real_escape_string($link, $_POST['catID']);
	$category = mysqli_real_escape_string($link, $_POST['category']);
	$sql = "UPDATE categories SET
			category='$category'
			WHERE catID='$catID'";
	if (!mysqli_query($link, $sql))
	{
		$error = 'Error updating submitted category.';
		include 'error.html.php';
		exit();
	}

	header('Location: .');
	exit();
}


if (isset($_POST['action']) and $_POST['action'] == 'Delete')
{
	include(__ROOT__ . "/includes/dbAdmin.inc.php");
	$id = mysqli_real_escape_string($link, $_POST['catID']);

	// Get items with certain category
	$sql = "SELECT itemID FROM items WHERE catID='$id'";
	$item_result = mysqli_query($link, $sql);
	
	if (!$item_result)
	{
		$error = 'Error getting list of items to delete: ' . mysqli_error($link);
		include 'error.html.php';
		exit();
	}
	
		
	$sql = "SELECT catID, category FROM categories WHERE catID='$id'";
	$category_result = mysqli_query($link, $sql);
	
	if (!$category_result)
	{
		$error = 'Error getting category to display: ' . mysqli_error($link);
		include 'error.html.php';
		exit();
	}

	
	// assume that no match has been found
		$recordsExist = false;
		
		
	// check whether recordset found any matches
	if (mysqli_num_rows($item_result) > 0) {

		$recordsExist = true;
		
		list($catID, $category) = mysqli_fetch_row($category_result);

	 	include 'category_delete.html.php';
		exit();

 	 	}
			elseif (mysqli_num_rows($item_result) == 0) {
			
			list($catID, $category) = mysqli_fetch_row($category_result);
			
			include 'category_delete.html.php';
			exit();
			}	
}


	 // Delete the category
		
if (isset($_POST['action']) and $_POST['action'] == 'Confirm deletion')
{
		include(__ROOT__ . "/includes/dbAdmin.inc.php");
		$id = mysqli_real_escape_string($link, $_POST['catID']);
		
		$sql = "DELETE FROM categories WHERE catID='$id'";
		if (!mysqli_query($link, $sql))
			{
				$error = 'Error deleting category: ' . mysqli_error($link);
				include 'error.html.php';
				exit();
			}
			
			header('Location: .');
			exit();
}


// Display category list
include(__ROOT__ . "/includes/dbAdmin.inc.php");
$result = mysqli_query($link, 'SELECT catID, category FROM categories');
if (!$result)
{
	$error = 'Error fetching categories from database! &#8211; ' . mysqli_error($link);
	include 'error.html.php';
	exit();
}

while ($row = mysqli_fetch_array($result))
{
	$categories[] = array('catID' => $row['catID'], 'category' => $row['category']);
}

include 'categories.html.php';
?>

The error is self-explanatory – you use a variable which is not defined before using it, and you’re not supposed to do that. Either check if it’s defined in the template, or initialize it with an empty string.

You also have some odd code –

if (isset($_GET['addform']))
{
    include(__ROOT__ . "/includes/dbAdmin.inc.php");

    $category = mysqli_real_escape_string($link, $_POST['category']);

if (isset($_GET['editform']))
{
    include(__ROOT__ . "/includes/dbAdmin.inc.php");

    $catID = mysqli_real_escape_string($link, $_POST['catID']);
    $category = mysqli_real_escape_string($link, $_POST['category']);

An HTTP request is of one method – GET, or POST, or HEAD, etc.

It is not possible for $_GET[‘addform’] and $_POST[‘category’] to be populated at the same time

It is not possible for $_GET[‘editform’] and $_POST[‘category’] to be populated at the same time

Since you are submitting the form with POST requests, you should read those variables from $_POST, not $_GET

Thanks I’ve now initialised the $category variable and the error went away. Regarding your comment on some odd code, when the user clicks on the following link:

<p><a href=“?add”>Add new category</a></p>

…it submits back to the controller and runs the following code:

if (isset($_GET['add']))
{
	$pagetitle = 'New category';
	$action = 'addform';
	$category = '';
	$catID = '';
	$button = 'Add author';

	include 'form.html.php';
	exit();
}

When form.html.php is included, the form on that page is populated with the above variables, one of which is the $action variable whose value is ‘addform’. So when that form is submitted with the action of:

<form action=“?addform” method=“post”>

…then it submits again back to the controller file where the following block is executed:

if (isset($_GET['addform']))
{
	include(__ROOT__ . "/includes/dbAdmin.inc.php");

	$category = mysqli_real_escape_string($link, $_POST['category']);
	$sql = "INSERT INTO categories SET
			category='$category'";
	if (!mysqli_query($link, $sql))
	{
		$error = 'Error adding submitted category.';
		include 'error.html.php';
		exit();
	}

	header('Location: .');
	exit();
}

The above runs because it detected the ?addform query string that’s stored in the $_GET array. Then the $category which is in this line here:

<label for="name">Category: <input type="text" name="category" id="category" value="<?php htmlout($category); ?>"/></label>

…is stored in the $_POST array back in the controller file

$category = mysqli_real_escape_string($link, $_POST[‘category’]

…so it’s ready to be inserted into the database.

It seems logical to me so I’m still not sure about the comment on the odd code. It all runs correctly also. I’m still only learning php so would appreciate if you could comment further on this?