包含函数php,给出旧代码中的错误


Include function php giving error from old code?

所以我遇到的问题是我在书中做的这个基本数据库应用程序练习。基本上,当您尝试将产品添加到数据库中时,如下面的代码所示,它会进行检查以确保所有字段都已填写完毕。但是,在执行查询的最后,当我有include('home.php')时,会发生这样的情况:当我返回到home.php页面并单击该页面上的一个链接时,如果其中一个字段为空,我会得到错误。有什么想法吗?

<?php
// Get the product data
$category_id = $_POST['category_id'];
$code = $_POST['code'];
$name = $_POST['name'];
$price = $_POST['price'];
// Validate inputs
if (empty($code) || empty($name) || empty($price) ) {
    $error = "Invalid product data. Check all fields and try again.";
    include('error.php');
} else {
    // If valid, add the product to the database
    require_once('database.php');
    $query = "INSERT INTO products
                 (categoryID, productCode, productName, listPrice)
              VALUES
                 ('$category_id', '$code', '$name', '$price')";
    $db->exec($query);
    // Display the Product List page
   include('home.php') ;
}
?>

没有html/css 的home.php

<?php
require_once('database.php');
    // Get category ID
    if(!isset($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);

?>

在文件home.php中,使用$_GET而不是$_POST:

更改此项:

 $category_id = $_GET['category_id'];

收件人:

$category_id = $_POST['category_id'];