Click here to Skip to main content
15,392,679 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
hello I using this code in my other table and it work fine but when I use it on product table will not add new product before I did the code I used XAMPP to insert data but now created a form the same as the other table and I want to make a dropdown menu that take data form prdct_cat a but the data will not go to data base only the image I choose will go the file not to database table

What I have tried:

my php connecting and the functions:
<pre lang="PHP">
<pre>
```
<?php

	class Pro
	{
		private $servername = "localhost";
		private $username   = "root";
		private $password   = "";
		private $dbname     = "cart_system";
		public  $con;


		// Database Connection 
		public function __construct()
		{
		    try {
			$this->con = new mysqli($this->servername, $this->username, $this->password, $this->dbname);	
		    } catch (Exception $e) {
			echo $e->getMessage();
		    }
		}

		// Insert Product
		public function insertData($name,$price,$qty,$code,$cat, $file)
		{	
			$allow = array('jpg', 'jpeg', 'png');
		   	$exntension = explode('.', $file['name']);
		   	$fileActExt = strtolower(end($exntension));
		   	$fileNew = rand() . "." . $fileActExt;  // rand function create the rand number 
		   	$filePath = 'uploads/'.$fileNew; 
			
			if (in_array($fileActExt, $allow)) {
    		          if ($file['size'] > 0 && $file['error'] == 0) {
		            if (move_uploaded_file($file['tmp_name'], $filePath)) {
		   		$query = "INSERT INTO product(product_name, product_price, product_qty,product_image,product_code,prdct_cat)
					VALUES('$name','$price','$qty','$fileNew','$code','$cat')";
				$sql = $this->con->query($query);
				if ($sql==true) {
				   return true;
				}else{
				  return false;
			    }   		    
		        }
		      }
		   }
		}

		// Fetch Product records for show listing

		public function displayData()
		{
		    $sql = "SELECT * FROM product";
		    $query = $this->con->query($sql);
		    $data = array();
		    if ($query->num_rows > 0) {
			while ($row = $query->fetch_assoc()) {
			    $data[] = $row;
			}
			return $data;
		    }else{
			return false;
		    }
		}

		// delete form Product
		public function delData($id)
		{	
		   		$query = "DELETE FROM product WHERE id = $id";
				$sql = $this->con->query($query);
				if ($sql==true) {
				   return true;
				}else{
				  return false;
			    }   		    

		   
		}

	}
?>



my add.php page

PHP
<pre><?php

// Include database file
include 'DbConnection.php';

$Obj_pro = new Pro();

// Insert Record in product table
if(isset($_POST['submit'])) {

    $name = $_POST['name'];
    $price = $_POST['price'];
    $qty = $_POST['qty'];
    $code = $_POST['code'];
    $cat = $_POST['cat'];
    $file = $_FILES['img'];
    $insertData = $Obj_pro->insertData($name, $price, $qty, $code, $cat, $file);

    if ($insertData){
        header("Location:../pro.php");
      
    }else{
        return false;
    }

}
?>
<!DOCTYPE html>
<html >
  <head>
    <title>إضافة منتج جديد</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  </head>
  <body class="bg-dark"> 
    <div class=" card text-center" style="padding:15px;" >
      <h4>اضافة منتح جديد في الموقع</h4>
    </div><br><br> <br><br> <br>
    <div class="container">
      <form method="POST" action="add.php" enctype="multipart/form-data">
        <div class="form-group text-right text-light">
          <label for="name">:اسم المنتج</label>
          <input type="text" class="form-control text-right" name="name" placeholder="الرجاء كتابة المنتج" required="">
        </div>
        <div class="form-group text-right text-light">
          <label for="username">:السعر</label>
          <input type="text" class="form-control text-right" name="price" placeholder="الرجاء كتابة السعر" required="">
        </div>
        <div class="form-group text-right text-light">
          <label for="username">:الكمية</label>
          <input type="text" class="form-control text-right" name="qty" placeholder="الرجاء كتابة الكمية" required="">
        </div>
        <div class="form-group text-right text-light">
          <label for="username">:الكود</label>
          <input type="text" class="form-control text-right" name="code" placeholder="الرجاء كتابة الكود" required="">
        </div>
        <div class="form-group text-right text-light">
          <label for="username">:التصنيف</label>
          <input type="text" class="form-control text-right" name="cat" placeholder="الرجاء كتابة التصنيف" >
          
        </div>
        <div class=" text-right form-group text-light">
          <label for="profile_image"> إضافة صورة</label>
          <input type="file" class="form-control" name="img" required=""> <br>
          <a href="../pro.php"   class="btn btn-light btn-right">إلغاء</a>
          <input type="submit" name="submit" class="btn btn-danger" style="float:right;" value="إضافة"></a>
        </div>
      </form>
    </div>
  </body>
</html>
Posted
Updated 29-May-22 19:53pm

1 solution

Hello !

you have HTML errors :
don't use native keywords as 'name' or 'id',
see in your code :

name="submit"
name="img"

keep 'img' and 'submit' at their place, it's HTML keywords.
the DOM of the page is a lazy ( fast/multi-purposes ) engine, and your page is in bug. ( as the form part ).

another error :
when you enclose your 'submit button' with a link ( href= , the server have to send 2 page "../pro.php", then one another by php script. It's cycling and redundancy call of resources.
the use of the php 'header' is favorite for your need.

for your datas that are not handled,
the picture handling and the $_POST contents encounts a problem

make echo($_POST['cat']); to see if the datas reach the server.
It's debuging by tracing your vars.


few tricks and shorcuts for your php :

-------------
in your DB class :

*__construct
*_execute_query($the_query String){ ..... ; }
*_get_result_of_query($the_query String ){ .......;}

INSERT / UPDATE / DELETE don't return a collection; ( _execute_query ) : imperative
but SELECT query does retur a collection. ( _get_result_of_query ) : selective

It's two sided transactions. "come"/"go"

If you make one function for every query in your app, you'll have hundred miles DB class to write, really.
use String query as input ( for 2 functions only ).
------------------

$insertData = $Obj_pro->insertData($name, $price, $qty, $code, $cat, $file);

    if ($insertData){
        header("Location:../pro.php");
      
    }else{

----
you can write : and gain less instructions to write to achieve
if( $Obj_pro->insertData($name, $price, $qty, $code, $cat, $file) ){
 ... it works; }
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900