2024/8/1 13:32:45 ![]()
根据上面的数据库设计,编写对应的PHP代码实现全部的API效果。
2024/8/1 13:32:45 
好的,下面是基于上述数据库设计编写的PHP代码,展示了如何实现全部的API效果。为了简洁起见,这里每个功能只展示了关键部分的代码。
### 项目结构我们假设项目结构如下:
```project/│├── api/│ ├── database.php│ ├── users.php│ ├── classes.php│ ├── courses.php│ ├── videos.php│ ├── tests.php│ └── comments.php├── .htaccess└── index.php```
### database.php```phpclass Database { private $host = 'localhost'; private $db_name = 'educational_management'; private $username = 'root'; private $password = ''; public $conn;
public function getConnection() { $this->conn = null; try { $this->conn = new PDO("mysql:host={$this->host};dbname={$this->db_name}", $this->username, $this->password); $this->conn->exec("set names utf8"); } catch(PDOException $exception) { echo "Connection error: " . $exception->getMessage(); } return $this->conn; }}```
### index.php```phpheader("Access-Control-Allow-Origin: *");header("Content-Type: application/json; charset=UTF-8");
require_once 'api/database.php';
// Instantiate database$database = new Database();$db = $database->getConnection();
// Route requests based on the URL$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));switch ($request[0]) { case 'users': include 'api/users.php'; break; case 'classes': include 'api/classes.php'; break; case 'courses': include 'api/courses.php'; break; case 'videos': include 'api/videos.php'; break; case 'tests': include 'api/tests.php'; break; case 'comments': include 'api/comments.php'; break; default: http_response_code(404); echo json_encode(array("message" => "Endpoint Not Found.")); break;}```
### users.php```phpif ($_SERVER['REQUEST_METHOD'] == 'POST') { $data = json_decode(file_get_contents("php://input")); $query = "INSERT INTO users (username, password, email, role, avatar) VALUES (:username, :password, :email, :role, :avatar)"; $stmt = $db->prepare($query);
$stmt->bindParam(':username', $data->username); $stmt->bindParam(':password', $data->password); $stmt->bindParam(':email', $data->email); $stmt->bindParam(':role', $data->role); $stmt->bindParam(':avatar', $data->avatar);
if($stmt->execute()) { http_response_code(201); echo json_encode(array("message" => "User was created.")); } else { http_response_code(503); echo json_encode(array("message" => "Unable to create user.")); }} elseif ($_SERVER['REQUEST_METHOD'] == 'GET') { $query = "SELECT * FROM users"; $stmt = $db->prepare($query); $stmt->execute(); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($users);}```
### classes.php```phpif ($_SERVER['REQUEST_METHOD'] == 'POST') { $data = json_decode(file_get_contents("php://input")); $query = "INSERT INTO classes (class_name, description, semester) VALUES (:class_name, :description, :semester)"; $stmt = $db->prepare($query);
$stmt->bindParam(':class_name', $data->class_name); $stmt->bindParam(':description', $data->description); $stmt->bindParam(':semester', $data->semester);
if($stmt->execute()) { http_response_code(201); echo json_encode(array("message" => "Class was created.")); } else { http_response_code(503); echo json_encode(array("message" => "Unable to create class.")); }} elseif ($_SERVER['REQUEST_METHOD'] == 'GET') { $query = "SELECT * FROM classes"; $stmt = $db->prepare($query); $stmt->execute(); $classes = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($classes);}```
### courses.php```phpif ($_SERVER['REQUEST_METHOD'] == 'POST') { $data = json_decode(file_get_contents("php://input")); $query = "INSERT INTO courses (course_name, description, syllabus) VALUES (:course_name, :description, :syllabus)"; $stmt = $db->prepare($query);
$stmt->bindParam(':course_name', $data->course_name); $stmt->bindParam(':description', $data->description); $stmt->bindParam(':syllabus', $data->syllabus);
if($stmt->execute()) { http_response_code(201); echo json_encode(array("message" => "Course was created.")); } else { http_response_code(503); echo json_encode(array("message" => "Unable to create course.")); }} elseif ($_SERVER['REQUEST_METHOD'] == 'GET') { $query = "SELECT * FROM courses"; $stmt = $db->prepare($query); $stmt->execute(); $courses = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($courses);}```
### videos.php```phpif ($_SERVER['REQUEST_METHOD'] == 'POST') { $data = json_decode(file_get_contents("php://input")); $query = "INSERT INTO videos (course_id, title, description, url) VALUES (:course_id, :title, :description, :url)"; $stmt = $db->prepare($query);
$stmt->bindParam(':course_id', $data->course_id); $stmt->bindParam(':title', $data->title); $stmt->bindParam(':description', $data->description); $stmt->bindParam(':url', $data->url);
if($stmt->execute()) { http_response_code(201); echo json_encode(array("message" => "Video was uploaded.")); } else { http_response_code(503); echo json_encode(array("message" => "Unable to upload video.")); }} elseif ($_SERVER['REQUEST_METHOD'] == 'GET') { $query = "SELECT * FROM videos"; $stmt = $db->prepare($query); $stmt->execute(); $videos = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($videos);}```
### tests.php```phpif ($_SERVER['REQUEST_METHOD'] == 'POST') { $data = json_decode(file_get_contents("php://input")); $query = "INSERT INTO tests (course_id, question, answer, type) VALUES (:course_id, :question, :answer, :type)"; $stmt = $db->prepare($query);
$stmt->bindParam(':course_id', $data->course_id); $stmt->bindParam(':question', $data->question); $stmt->bindParam(':answer', $data->answer); $stmt->bindParam(':type', $data->type);
if($stmt->execute()) { http_response_code(201); echo json_encode(array("message" => "Test was created.")); } else { http_response_code(503); echo json_encode(array("message" => "Unable to create test.")); }} elseif ($_SERVER['REQUEST_METHOD'] == 'GET') { $query = "SELECT * FROM tests"; $stmt = $db->prepare($query); $stmt->execute(); $tests = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($tests);}```
### comments.php```phpif ($_SERVER['REQUEST_METHOD'] == 'POST') { $data = json_decode(file_get_contents("php://input")); $query = "INSERT INTO comments (course_id, user_id, content) VALUES (:course_id, :user_id, :content)"; $stmt = $db->prepare($query);
$stmt->bindParam(':course_id', $data->course_id); $stmt->bindParam(':user_id', $data->user_id); $stmt->bindParam(':content', $data->content);
if($stmt->execute()) { http_response_code(201); echo json_encode(array("message" => "Comment was added.")); } else { http_response_code(503); echo json_encode(array("message" => "Unable to add comment.")); }} elseif ($_SERVER['REQUEST_METHOD'] == 'GET') { $query = "SELECT * FROM comments"; $stmt = $db->prepare($query); $stmt->execute(); $comments = $stmt->fetchAll(PDO::FETCH_ASSOC); echo json_encode($comments);}```
### .htaccess为了支持URL重写,将所有请求重定向到 `index.php`:
```RewriteEngine OnRewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)$ index.php [QSA,L]```
这段代码只是一个简单的示例,不包括所有可能的错误处理、验证和安全措施。在实际生产环境中,请确保为输入数据进行适当的验证,并使用准备好的语句以防止SQL注入等攻击。