使用PHP构建RESTFul API - 面向对象编程(OOP)、PDO与MySQL - DCodeMania

作者:API传播员 · 2026-01-12 · 阅读时间:6分钟

在这篇文章中,我们将学习如何使用 PHP 的面向对象编程(OOP)和 PDO(PHP 数据对象)结合 MySQL 数据库来RESTful Web 服务,我们可以轻松实现对 MySQL 数据库的 CRUD 操作(创建、读取、更新和删除)。本文将逐步展示如何实现常见的 HTTP 方法(如 GET、POST、PUT 和 DELETE)的功能,并使用 Postman 测试这些 API


步骤 1:创建项目目录

首先,打开您的 htdocswww 文件夹,创建一个新的项目目录,并将其命名为 restful。接着,用代码编辑器打开此目录。


步骤 2:创建数据库和表

在这一步,我们将为 RESTful API 创建一个数据库和表:

  1. 打开 PHPMyAdmin。
  2. 创建一个名为 restful 的新数据库。
  3. 在该数据库中创建一个名为 users 的表。

以下是表结构的示例:

数据库表结构


步骤 3:创建数据库配置文件

在项目的根目录中创建一个名为 config.php 的文件,用于管理数据库连接。以下是代码示例


conn = new PDO($this->dsn, self::DBUSER, self::DBPASS);
            $this->conn->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            die("连接失败:" . $e->getMessage());
        }
    }

    public function test_input($data) {
        $data = strip_tags($data);
        $data = htmlspecialchars($data);
        $data = stripslashes($data);
        $data = trim($data);
        return $data;
    }

    public function message($content, $status) {
        return json_encode(['message' => $content, 'error' => $status]);
    }
}
?>

此文件包含数据库连接的配置,并定义了两个实用方法:test_input 用于净化输入数据,message 用于以 JSON 格式返回消息和状态


步骤 4:创建数据库操作类

接下来,我们创建一个名为 db.php 的文件,用于定义所有与数据库交互的方法:


conn->prepare($sql);
        $stmt->execute(['id' => $id]);
        return $stmt->fetchAll();
    }

    public function insert($name, $email, $phone) {
        $sql = "INSERT INTO users (name, email, phone) VALUES (:name, :email, :phone)";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute(['name' => $name, 'email' => $email, 'phone' => $phone]);
        return true;
    }

    public function update($name, $email, $phone, $id) {
        $sql = "UPDATE users SET name = :name, email = :email, phone = :phone WHERE id = :id";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute(['name' => $name, 'email' => $email, 'phone' => $phone, 'id' => $id]);
        return true;
    }

    public function delete($id) {
        $sql = "DELETE FROM users WHERE id = :id";
        $stmt = $this->conn->prepare($sql);
        $stmt->execute(['id' => $id]);
        return true;
    }
}
?>

此文件扩展了 config.php,并定义了 fetchinsertupdatedelete 方法,用于操作数据库中的数据。


步骤 5:创建主入口文件

创建一个名为 users.php 的文件,这是 RESTful API 的主入口文件。以下是部分代码示例:


fetch($id) : $user->fetch();
    echo json_encode($data);
}

if ($api == 'POST') {
    $name = $user->test_input($_POST['name']);
    $email = $user->test_input($_POST['email']);
    $phone = $user->test_input($_POST['phone']);
    if ($user->insert($name, $email, $phone)) {
        echo $user->message("用户添加成功!", false);
    } else {
        echo $user->message("添加用户失败!", true);
    }
}

if ($api == 'PUT') {
    parse_str(file_get_contents("php://input"), $post_input);
    $name = $user->test_input($post_input['name']);
    $email = $user->test_input($post_input['email']);
    $phone = $user->test_input($post_input['phone']);
    if ($id) {
        if ($user->update($name, $email, $phone, $id)) {
            echo $user->message("用户更新成功!", false);
        } else {
            echo $user->message("更新用户失败!", true);
        }
    } else {
        echo $user->message("未找到用户!", true);
    }
}

if ($api == 'DELETE') {
    if ($id) {
        if ($user->delete($id)) {
            echo $user->message("用户删除成功!", false);
        } else {
            echo $user->message("删除用户失败!", true);
        }
    } else {
        echo $user->message("未找到用户!", true);
    }
}
?>

步骤 6:URL 重写

为了使 URL 更加友好,我们可以创建一个 .htaccess 文件,内容如下:

RewriteEngine On
RewriteRule ^users/?$ users.php [NC,L]
RewriteRule ^users/([0-9]+)/?$ users.php?id=$1 [NC,L]

通过此配置,http://localhost/restful/users.php?id=5 可被重写为 http://localhost/restful/users/5


步骤 7:使用 Postman 测试 API

使用 Postman 测试 RESTful API 是一种快速验证功能的方法。以下是一些测试示例:

  1. POST 方法:添加新用户。

  2. GET 方法:获取所有用户。

  3. GET 方法(单个用户):通过 ID 获取用户。

  4. PUT 方法:更新用户信息。

  5. DELETE 方法:删除用户。

通过这些操作,您可以验证 API 的每个功能是否正常工作。


希望这篇文章对您有所帮助!如果有任何问题,请随时留言。

原文链接: https://dcodemania.com/post/restful-api-using-php-oop-pdo