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

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记