PHP MySQL REST API for Products: Full CRUD Operation
Step 1: Set Up the MySQL Database
Run the following SQL commands to set up the database and table:
Step 2: Create the PHP Files
- Database connection (
db.php
) - API functionality (
product.php
) - API endpoints (
index.php
)
Step 3: Database Connection (db.php
)
Create a file named db.php
:
Step 4: Product Class (product.php
)
Create a file named product.php
:
Step 5: API Endpoints (index.php
)
Create a file named index.php
:
Step 6: Testing the API
1. GET (Retrieve Products)
- All Products:
GET /index.php/products
- Single Product:
GET /index.php/products/{id}
2. POST (Create Product)
Send a JSON payload to create a new product:
- Endpoint:
POST /index.php/products
3. PUT (Update Product)
Send a JSON payload to update an existing product:
- Endpoint:
PUT /index.php/products/{id}
4. DELETE (Delete Product)
- Endpoint:
DELETE /index.php/products/{id}