Hi.

My page has a men that holds categories of products, some of these categoriees have subcategories, some dont.
I have mysql tables category, subcategory and products.
My code right now only adds products to the subcategories, it takes the id value of subcategory and puts it in the product_id field of products. this is my code to do so

<?php
include '../../inc/connect.php';


   // file needs to be jpg,gif,bmp,x-png
   if (($_FILES["image_upload_box"]["type"] == "image/jpeg" || $_FILES["image_upload_box"]["type"] == "image/pjpeg" || $_FILES["image_upload_box"]["type"] == "image/gif" || $_FILES["image_upload_box"]["type"] == "image/x-png") && ($_FILES["image_upload_box"]["size"] < 8000000)){

     // if uploaded image was JPG/JPEG
      if($_FILES["image_upload_box"]["type"] == "image/jpeg" || $_FILES["image_upload_box"]["type"] == "image/pjpeg"){
         $image_source = imagecreatefromjpeg($_FILES["image_upload_box"]["tmp_name"]);
      }
      // if uploaded image was GIF
      if($_FILES["image_upload_box"]["type"] == "image/gif"){
         $image_source = imagecreatefromgif($_FILES["image_upload_box"]["tmp_name"]);
      }
      // BMP doesn't seem to be supported so remove it form above image type test (reject bmps)
      // if uploaded image was BMP
      if($_FILES["image_upload_box"]["type"] == "image/bmp"){
         $image_source = imagecreatefromwbmp($_FILES["image_upload_box"]["tmp_name"]);
      }
      // if uploaded image was PNG
      if($_FILES["image_upload_box"]["type"] == "image/x-png"){
         $image_source = imagecreatefrompng($_FILES["image_upload_box"]["tmp_name"]);
      }
      $remote_file = "../../images/products/".$_FILES["image_upload_box"]["name"];
      imagejpeg($image_source,$remote_file,100);
      chmod($remote_file,0644);

      imagejpeg($image_source,$remote_file,100);
      chmod($remote_file,0644);


               $thumb_height = 150;
               $thumb_width = 150;
               list($image_width, $image_height) = getimagesize($remote_file);
               if($image_width>$thumb_width || $image_height >$thumb_height){
                  $proportions = $image_width/$image_height;
                  $new_height = $thumb_height;
                  $new_width = round($thumb_height*$proportions);
                  $thumb_image = imagecreatetruecolor($new_width , $new_height);
                  $image_source = imagecreatefromjpeg($remote_file);
                  imagecopyresampled($thumb_image, $image_source, 0, 0, 0, 0, $new_width, $new_height, $image_width, $image_height);
                  imagejpeg($thumb_image,$remote_file,100);
                  imagedestroy($thumb_image);
         $cat = intval($_POST['subcat']);
         $aname = $_POST['aname'];
         $aprice= $_POST['aprice'];
         $adescription = $_POST['adescription'];
         $description = mysql_real_escape_string($adescription);
         $name = mysql_real_escape_string($aname);
         $query = "INSERT INTO products VALUES('', '$name', '$description', '$aprice', '$cat', '$remote_file')";
         $result = mysql_query($query);
         if(!$result){
          echo 'Something went wrong';
         }
         header( 'Location: ../productadd.php' ) ;
     }
}


?> 

How do i modify this so that IF a category has no subcategory then the id from category gets added as product_id in products.

Or if there is a better way to do this?

Thanks....

Dani AI

Generated

Short summary and practical fix tied to the thread: the current upload handler only reads $_POST['subcat'], so any product added when its category has no subcategories never gets a valid category id. The simplest reliable approach is to submit both a category and an optional subcat field and, on the server, store the subcategory id if present or fall back to the category id when no subcat exists. This follows 's idea of separate controls for Category and SubCategory.

A minimal server-side decision (use parameterized queries; avoid deprecated mysql_* functions):

$catId = isset($_POST['category']) ? (int) $_POST['category'] : 0;
$subId = isset($_POST['subcat'])   ? (int) $_POST['subcat']   : 0;

$assignedId = $subId ?: $catId;

$stmt = $pdo->prepare(
  "INSERT INTO products (name, description, price, product_category_id, image) VALUES (?, ?, ?, ?, ?)"
);
$stmt->execute([$name, $description, $price, $assignedId, $imagePath]);

Better long-term schema: give products both category_id and nullable subcategory_id. That removes ambiguity when querying (list all products in a category should include products with no subcategory and those grouped by subcategory). Example insert pattern:

$stmt = $pdo->prepare(
  "INSERT INTO products (name, description, price, category_id, subcategory_id, image) VALUES (?, ?, ?, ?, ?, ?)"
);
$subIdParam = $subId ?: null;
$stmt->execute([$name,$description,$price,$catId,$subIdParam,$imagePath]);

Practical notes and cautions: implement the UI so the subcategory select is populated (AJAX on category change) and hidden/cleared when no subcats exist (as suggested). Server-side verification must still check whether the chosen category actually has subcategories and accept the fallback. Use prepared statements (PDO or mysqli), validate/sanitize all inputs and uploaded files, create unique sanitized filenames, and add foreign keys/indexes for integrity and performance.

HI,
I am not good in PHP. so I am not looking into your code but i would like to give you some idea so you can apply in your code..
Take 3 controls.where you can select the Category,SubCategory and Products
Now First Control feel with Category.
second control which is SubCategory should be filled by CategoryID,
thierd Control which is Product shold be filled by either categoryID or SubCategoryID
You need 3 Pages also,
1)Where you can enter category
2) where you can enter suncategory with or without CategoryID
3) Where you can enter product with or without subcategoryID

->> so, it's all dependent from the master table to child table.

    you will get one power structure.

->> Hope I am clear but still if you find any difficulty to understand this. please let me know.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.