所以我遇到的问题是我从一本书中做的基本数据库应用程序练习。基本上,当您尝试将产品添加到数据库时,如下面的代码所示,它会检查以确保填写所有字段。但是,最后,当它执行查询并且我有 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') ;
}
?>
home.php没有html / css
<?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);
?>
答案 0 :(得分:1)
在home.php文件中,您使用$_GET
代替$_POST
:
改变这个:
$category_id = $_GET['category_id'];
要:
$category_id = $_POST['category_id'];