Below is a guide to creating a simple REST API using Webman PHP to connect to MySQL. In this example, we will perform the following operations:
- Query all data in the
users
table (withusername
andemail
fields). - Update the email based on
username
. - Delete data based on
username
.
1. Install Webman PHP
If you haven’t installed Webman PHP yet, you can do so via Composer:
composer create-project workerman/webman webman-api
cd webman-api
2. Configure MySQL Connection
In the .env
file (or create this file in the root directory of your project), add the MySQL connection information:
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password
3. Create the REST API Structure
Create a controller for the REST API. For example, create the file app/controller/UserController.php
:
<?php
namespace app\controller;
use support\Request;
use support\Db;
class UserController
{
// 1. Query all data in the users table
public function index(Request $request)
{
$users = Db::table('users')->select('username', 'email')->get();
return json($users);
}
// 2. Update email based on username
public function update(Request $request, $username)
{
$new_email = $request->input('email');
if (!$new_email) {
return json(['error' => 'Email is required'], 400);
}
Db::table('users')
->where('username', $username)
->update(['email' => $new_email]);
return json(['message' => 'Email updated successfully']);
}
// 3. Delete data based on username
public function delete(Request $request, $username)
{
Db::table('users')
->where('username', $username)
->delete();
return json(['message' => 'User deleted successfully']);
}
}
4. Routing
In the route/web.php
file, add the routes for the REST API:
use app\controller\UserController;
// Get all users
Route::get('/users', [UserController::class, 'index']);
// Update email by username
Route::post('/users/update/{username}', [UserController::class, 'update']);
// Delete user by username
Route::delete('/users/{username}', [UserController::class, 'delete']);
5. Run the Application
Run the Webman application with the following command:
php start.php start
6. Test the API
- Query all users: Send a GET request to
http://localhost:8787/users
. - Update email: Send a POST request to
http://localhost:8787/users/update/{username}
with the following JSON body:
{
"email": "[email protected]"
}
- Delete user: Send a DELETE request to
http://localhost:8787/users/{username}
.
This is a basic approach to creating a REST API with Webman PHP connected to MySQL. You can expand and modify it according to your project’s specific needs.
Leave a Reply