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

注意:第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 13: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'];
    
    已采纳该答案
    打赏 评论
  • dongzhiman2162 2012-01-21 13:14

    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;
    
    打赏 评论

相关推荐 更多相似问题