Tudor Ciotlos
Tudor Ciotlos

Reputation: 1845

Notice: Undefined index on line 5

I am getting the following error on a PHP & MySQL application from Murach's PHP and MySQL book:

Notice: Undefined index: category_id in C:\xampp\htdocs\book_apps\ch04_product_viewer\index.php on line 5

I didn't modified the code whatsoever (yet), so I assumed it should work out of the box. The application displays products from a database as it should, the only problem is I get this annoying error.

Here is the PHP code of the index.php file:

<?php
require 'database.php';

// Get category ID
$category_id = $_GET['category_id'];
if (!isset($category_id)) {
    $category_id = 1;
}

// Get name for current category
$query = "SELECT * FROM categories
          WHERE categoryID = $category_id";
$category = $db->query($query);
$category = $category->fetch();
$category_name = $category['categoryName'];

// Get all categories
$query = 'SELECT * FROM categories
          ORDER BY categoryID';
$categories = $db->query($query);

// Get products for selected category
$query = "SELECT * FROM products
          WHERE categoryID = $category_id
          ORDER BY productID";
$products = $db->query($query);
?>

Upvotes: 1

Views: 12949

Answers (2)

Pekka
Pekka

Reputation: 449415

It's a notice rather than an error, meaning PHP tells you something it thinks is wrong, but the code is executed unhindered. The reason is that if you don't pass category_id in the query string, the corresponding element in the GET array does not exist.

There is a lot of legacy PHP code that doesn't check for the existence of array elements - in those cases, it's often unavoidable to change the error reporting level to simply mute the notices. It can also be argued that accessing a GET parameter shouldn't trigger this kind of notice at all.

However, adjusting the error reporting level is regarded bad practice, as notices can often be very useful. So when writing new code, add the necessary checks so this doesn't happen.

The proper way to do this without getting a notice would be

if (isset($_GET['category_id']))
 $category_id = $_GET['category_id'];

Upvotes: 3

Michael Berkowski
Michael Berkowski

Reputation: 270607

Just check isset() first. If you attempt to assign it to $category_id when the $_GET['category_id'] index isn't present, PHP will issue a notice.

if (isset($_GET['category_id'])) {
    $category_id = intval($_GET['category_id']);
else {
    $category_id = 1;
}

Notice also that I have wrapped $_GET['category_id'] with intval() to protect against invalid input that could be used for SQL injection.

Shorthand version using a ternary operator:

$category_id = isset($_GET['category_id']) ? intval($_GET['category_id']) : 1;

Upvotes: 2

Related Questions