Create parking system API

Status: completed
All Tasks

Project: - No Project

Employee: -

Output Type:

Generated File: Not generated yet

Description

Write backend API for vehicle entry and exit using PHP and MySQL

AI Output

To create a simple backend API for vehicle entry and exit using PHP and MySQL, you'll need to set up your database, create the appropriate tables, and then develop the API endpoints.

### Step 1: Set Up Your MySQL Database

First, set up your MySQL database. Here's a sample SQL script to create a database and a table for vehicle records.

```sql
CREATE DATABASE vehicle_management;

USE vehicle_management;

CREATE TABLE vehicle_records (
    id INT AUTO_INCREMENT PRIMARY KEY,
    license_plate VARCHAR(20) NOT NULL UNIQUE,
    entry_time DATETIME,
    exit_time DATETIME,
    status ENUM('in', 'out') NOT NULL
);
```

### Step 2: Create Your PHP Project Structure

Create a directory for your project and structure it as follows:

```
vehicle_management/
    ├── api/
    │   ├── vehicle.php
    └── config.php
```

### Step 3: Create the Configuration File

In `config.php`, set up the database connection:

```php
<?php
$host = 'localhost';
$db = 'vehicle_management';
$user = 'your_username'; // Update with your DB user
$pass = 'your_password'; // Update with your DB password

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Could not connect to the database $db :" . $e->getMessage());
}
?>
```

### Step 4: Create the Vehicle Entry and Exit API

In `api/vehicle.php`, implement the API endpoints:

```php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET');

require '../config.php';

// Get the HTTP method
$method = $_SERVER['REQUEST_METHOD'];

// Handle vehicle entry
if ($method === 'POST' && isset($_GET['action']) && $_GET['action'] === 'entry') {
    $license_plate = $_POST['license_plate'] ?? '';

    if (empty($license_plate)) {
        echo json_encode(["error" => "License plate is required."]);
        http_response_code(400);
        exit;
    }

    // Check if vehicle already exists
    $stmt = $pdo->prepare("SELECT * FROM vehicle_records WHERE license_plate = :license_plate AND status = 'in'");
    $stmt->execute(['license_plate' => $license_plate]);
    
    if ($stmt->rowCount() > 0) {
        echo json_encode(["error" => "Vehicle is already inside."]);
        http_response_code(400);
        exit;
    }

    // Insert a new vehicle entry
    $stmt = $pdo->prepare("INSERT INTO vehicle_records (license_plate, entry_time, status) VALUES (:license_plate, NOW(), 'in')");
    $stmt->execute(['license_plate' => $license_plate]);
    
    echo json_encode(["success" => "Vehicle entry recorded."]);
    http_response_code(201);
}

// Handle vehicle exit
else if ($method === 'POST' && isset($_GET['action']) && $_GET['action'] === 'exit') {
    $license_plate = $_POST['license_plate'] ?? '';

    if (empty($license_plate)) {
        echo json_encode(["error" => "License plate is required."]);
        http_response_code(400);
        exit;
    }

    // Check if vehicle is inside
    $stmt = $pdo->prepare("SELECT * FROM vehicle_records WHERE license_plate = :license_plate AND status = 'in'");
    $stmt->execute(['license_plate' => $license_plate]);
    
    if ($stmt->rowCount() === 0) {
        echo json_encode(["error" => "Vehicle is not inside."]);
        http_response_code(400);
        exit;
    }

    // Update vehicle exit time
    $stmt = $pdo->prepare("UPDATE vehicle_records SET exit_time = NOW(), status = 'out' WHERE license_plate = :license_plate AND status = 'in'");
    $stmt->execute(['license_plate' => $license_plate]);
    
    echo json_encode(["success" => "Vehicle exit recorded."]);
    http_response_code(200);
}

// Handle getting vehicle status
else if ($method === 'GET') {
    $stmt = $pdo->query("SELECT * FROM vehicle_records ORDER BY entry_time DESC");
    $vehicles = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode($vehicles);
    http_response_code(200);
} else {
    echo json_encode(["error" => "Invalid request."]);
    http_response_code(405);
}
?>
```

### Step 5: Testing the API

Now you can test your API:

1. **Vehicle Entry**: Use a tool like Postman or cURL to send a POST request to `http://yourserver/api/vehicle.php?action=entry` with a form field `license_plate` containing the license plate number.

   Example using cURL:
   ```bash
   curl -X POST -d "license_plate=ABC123" http://yourserver/api/vehicle.php?action=entry
   ```

2. **Vehicle Exit**: Send a POST request to `http://yourserver/api/vehicle.php?action=exit` with the `license_plate` field.

   Example using cURL:
   ```bash
   curl -X POST -d "license_plate=ABC123" http://yourserver/api/vehicle.php?action=exit
   ```

3. **Get Vehicle Status**: Send a GET request to `http://yourserver/api/vehicle.php` to fetch all vehicle records.

   Example using cURL:
   ```bash
   curl http://yourserver/api/vehicle.php
   ```

### Additional Notes

- Ensure you handle exceptions and sanitize your inputs properly to avoid SQL injection.
- For a production environment, consider implementing more robust authentication, logging, and error handling.
- Depending on your needs, you might want to consider implementing a framework like Laravel or Slim for better structure and additional features.
Run Again Create New Task