我使用參數 id 在 php 中建立了一個 REST API GET 方法。 http://localhost:8012/REST-API/items/expenses?id=2。這工作正常,但我想使用 http://localhost:8012/REST-API/items/expenses?id=2&year=2022 來取得資料。我是 php 新手,嘗試了所有可能性,但沒有得到正確的回應。下面是程式碼
<?php class Expenses{ private $expensesTable = "expenses"; public $id; public $month; private $amount; public $year; public function __construct($db){ $this->conn = $db; } function expenses(){ if($this->year) { $stmt = $this->conn->prepare("SELECT * FROM ".$this->expensesTable." WHERE year = ?"); $stmt->bind_param("i", $this->year); } else if($this->id) { $stmt = $this->conn->prepare("SELECT * FROM ".$this->expensesTable." WHERE id = ?"); $stmt->bind_param("i", $this->id); } else if($this->id && $this->year) { $stmt = $this->conn->prepare("SELECT * FROM ".$this->expensesTable." WHERE id = ? AND year= ?"); $stmt->bind_param("i", $this->id,$this->year); } else { $stmt = $this->conn->prepare("SELECT * FROM ".$this->expensesTable); } $stmt->execute(); $result = $stmt->get_result(); return $result; } } ?>
<?php header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); include_once '../config/Database.php'; include_once '../class/Expenses.php'; $database = new Database(); $db = $database->getConnection(); $expenses = new Expenses($db); $expenses->id = (isset($_GET['id']) && $_GET['id']) ? $_GET['id'] : '0'; $expenses->year = (isset($_GET['year']) && $_GET['year']) ? $_GET['year'] : '0'; $expenses->extra = (isset($_GET['month']) && $_GET['month']) ? $_GET['month'] : '0'; $result = $expenses->expenses(); if($result->num_rows > 0){ $itemRecords=array(); $itemRecords["expenses"]=array(); while ($expense = $result->fetch_assoc()) { extract($expense); $itemDetails=array( "id" => $id, "month" => $month, "amount" => $amount, "year" => $year ); array_push($itemRecords["expenses"], $itemDetails); } http_response_code(200); echo json_encode($itemRecords); }else{ http_response_code(404); echo json_encode( array("message" => "No item found.") ); }
RewriteEngine On # Turn on the rewriting engine RewriteRule ^read$ read.php [NC,L] RewriteRule ^read/([0-9_-]*)$ read.php?id= [NC,L] RewriteRule ^create$ create.php [NC,L] RewriteRule ^update$ update.php [NC,L] RewriteRule ^delete$ delete.php [NC,L] RewriteRule ^expenses$ readexpenses.php [NC,L] RewriteRule ^expenses/([0-9_-]*)$ readexpenses.php?year= [NC,L] RewriteRule ^expenses/([0-9_-]*)$ readexpenses.php?id= [NC,L] RewriteRule ^expenses/([0-9_-]*)$ readexpenses.php?id=&year= [NC,L]###
正如我在評論中所說,他最後三個規則是錯誤的:
這個網址會發生什麼事?
http://example.com/expenses/2012
如何偵測這是id
或year
?我建議使用這個方案:
因此
.htaccess
檔案將是:(剛剛更改了最後三個規則)線上測試:
我已經測試過了,它在任何情況下都有效
,你可以看到它通過了該url
您也應該更改您的 php 條件id /年
#,id## 和
年份