douzhi2012 2012-01-21 05:13
浏览 34
已采纳

注意:第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);
?>

展开全部

  • 写回答

2条回答 默认 最新

  • doume5227 2012-01-21 05:15
    关注

    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'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?