APIs to Upload form data with file in PHP & MYSQL

In the earlier tutorial, you learnt to filter products by id and by name, limit the number of rows to return, and count products. In this tutorial, we will create more APIs to upload product form data with image file, and to delete products from MYSQL database. The uploaded files are stored in local storage (uploads folder).

Open Controllers/ProductController.php file to add three more methods to handle product inserting, updating, and deleting. In PHP, form data submitted from a client app is available in $_POST variable and uploaded files will be in $_FILES variable.  In the addProduct() and updateProduct() methods, we simply get data from the POST variable and insert or update the data to MYSQL database using Prepared Statements.  To save the uploaded files to local storage, use move_uploaded_file() method. The deleteProduct() required one parameter - pid to delete a product by its id from the database.

.........................

public function addProduct()
	{
		
		try {
			
			if(isset($_POST)){
				// Form Data from client app
				$name=$_POST["name"]; 
				$description=$_POST["description"];
				$slug=$_POST["slug"];
				$price=$_POST["price"];
				$category=$_POST["category"];
				$subcategory=$_POST["subcategory"];
				
				$sql = "INSERT INTO products (name,description, price, slug, category_id,subcategory_id) VALUES(?,?,?,?,?,?)";
				$stmt = $this->con->prepare($sql);
				$stmt->bind_param('ssdsii',$name,$description,$price,$slug,$category,$subcategory);		
				if($stmt->execute()){
					if(isset($_FILES['image'])){
						  
							$target_path = "./uploads/";

							$filenames=$_FILES['image']["name"];                                    
        					$filetemps=$_FILES['image']["tmp_name"];

							if(move_uploaded_file($filetemps[0],$target_path.$filenames[0])){
						
								$this->con->query("UPDATE products set thumbnail='$filenames[0]' WHERE id=$stmt->insert_id");
							}
						    echo json_encode(['status'=>200,'data'=>$filenames[0]]);
					}
					else{
						echo json_encode(['status'=>200,'data'=>$name]);
					}
				
				} 
				else{
					echo json_encode(['status'=>300,'data'=>'failed to save data in database']);
				}
			}
			else{
				echo json_encode(['status'=>300,'data'=>'no post data']);
			   }
			}  
	            catch (Exception $e) {
			echo json_encode(['status'=>300,'data' => 'Failed to save the product']);
		}
			  

	}
	
	public function updateProduct(int $pid)
	{
		
		try {
			if(isset($_POST)){ // Form Data from client app

				$name=$_POST["name"];
				$id=$_POST["id"];
				$description=$_POST["description"];
				$slug=$_POST["slug"];
				$price=$_POST["price"];
				$category=$_POST["category"];
				$subcategory=$_POST["subcategory"];
				

				$sql = "UPDATE products SET name=?, description=?, price=?, slug=?, category_id=?,subcategory_id=? WHERE id=?";
				if($stmt = $this->con->prepare($sql)){
					$stmt->bind_param('ssdsiii',$name,$description,$price,$slug,$category,$subcategory,$id);		
					if($stmt->execute()){
						
						if(isset($_FILES['image'])){
							$target_path = "./uploads/";
							$filenames=$_FILES['image']["name"];                                    
        					$filetemps=$_FILES['image']["tmp_name"];

							if(move_uploaded_file($filetemps[0],$target_path.$filenames[0])){
						
							 $this->con->query("UPDATE products set thumbnail='$filenames[0]' WHERE id=$id");
							}
							echo json_encode(['status'=>200,'data'=>$filenames[0]]);
						}
						else{
							echo json_encode(['status'=>200,'data'=>$name]);
						}
						
					}
					else{
						echo json_encode(['status'=>300,'data'=>' error in updating data to database']);
					} 
				}else{
					echo json_encode(['status'=>300,'data'=>' error in updating data to database']);
				}
			 }
		    
		  }
		  
		  catch (Exception $e) {
			echo json_encode(['status'=>300,'data' => 'Failed to update the product']);
		  }
		 

	}
	public function deleteProduct(int $pid)
	{
		
		try {
				$sql = "DELETE FROM products  WHERE id=?";
				if($stmt = $this->con->prepare($sql)){
					$stmt->bind_param('i',$pid);		
					if($stmt->execute()){
						
						echo json_encode(['status'=>200,'data'=>$pid]);

					}
					else{
						echo json_encode(['status'=>300,'data'=>' error to delete the product from database']);
					} 
				}else{
					echo json_encode(['status'=>300,'data'=>' error to delete the product from database']);
				}
			 
		    
		  }
		  
		  catch (Exception $e) {
			echo json_encode(['status'=>300,'data' => 'Failed to delete the product']);
		  }
		 

	}
....................

In the routes/web.php file, add three more routes to handle product inserting, updating, and deleting:
$routes->add('addproduct', new Route(constant('URL_SUBFOLDER') . '/products/add', array('controller' => 'ProductController', 'method'=>'addProduct'), array()));
routes->add('editproduct', new Route(constant('URL_SUBFOLDER') . '/products/{id}', array('controller' => 'ProductController', 'method'=>'editProduct'), array('id' =>'[0-9]+')));
$routes->add('deleteproduct', new Route(constant('URL_SUBFOLDER') . '/products/{id}/delete', array('controller' => 'ProductController', 'method'=>'deleteProduct'), array('id' =>'[0-9]+')));

Save the project. The APIs is ready to test! 

Add ARC extension to chrome. From chrome://apps, open ARC. Make sure MYSQL is running.
On ARC, to insert from data with file, select method POST. The Request URL is http://localhost/mysite/api/products/add. Add Content-Type header. To sent form data with file, the value of the content type header has to be multipart/form-data. When Body part is ready, press SEND to upload the form data.



To update a specific product. Let say the product with id 1. Select method PUT. The Request URL is http://localhost/mysite/api/products/1. Make changes to the Body part and press SEND to update the product in the database.

To delete the id-1 product, select method DELETE. The Request URL is http://localhost/mysite/api/products/1/delete. 

Comments

Popular posts from this blog

Create Angular App & SideBar

PHP Mysql Database Migration Using Phinx