<?php
// initializing variables
$pname = "";
$pprice = "";
$pdetails = "";
$image = "";
$errors = array(); 
// connect to the database
$db = mysqli_connect('localhost', 'root', '', 'shopping');

// UPLOAD IMAGE
if(isset($_POST['submit_button'])) {
  // receive all input values from the form
  $pname = mysqli_real_escape_string($db, $_POST['pname']);
  $pprice = mysqli_real_escape_string($db, $_POST['pprice']);
  $pdetails = mysqli_real_escape_string($db, $_POST['pdetails']);

  $image   = isset($_POST['image'])?$_POST['image']:'';
  $uploads_dir = 'uploads/product';
  $img_path = 'http://localhost/folder/uploads/product/';
  $tmp_name = $_FILES["image"]["tmp_name"];
  $name = basename($_FILES["image"]["name"]);
  move_uploaded_file($tmp_name, "$uploads_dir/$name");
  $p_img_url =  $img_path.$name;    
  if(!empty($name))
   {
    $p_img_url = $img_path.$name;
   }
   else
    {
      $p_img_url = '';
    }

  if (empty($pname)) { array_push($errors, "Name is required"); }
  if (empty($pprice)) { array_push($errors, "Price is required"); }
  if (empty($pdetails)) { array_push($errors, "Details is required"); }
  
  // first check the database to make sure 
  // a user does not already exist with the same product
  $product_check_query = "SELECT * FROM products WHERE product_name='$pname' LIMIT 1";
  $result = mysqli_query($db, $product_check_query);
  $product = mysqli_fetch_assoc($result);

  // Finally, register user if there are no errors in the form
  if (count($errors) == 0) {
    
    $query = "INSERT INTO products(product_name,product_price,product_details,image_dir) VALUES ('$pname','$pprice','$pdetails','$p_img_url')";

  if (mysqli_query($db,$query)) 
  {
    $_SESSION['pname'] = $pname;
    echo '<script>alert("Product Added successfully");</script>'; 
  }
 }
}
?>