PHP REST API GET多参数(id+year)查询功能实现问题求助
问题修复方案
1. 修正Expenses.php的条件逻辑与参数绑定
原代码的条件判断顺序有误,当同时传入id和year时,会优先触发单一参数的分支,永远走不到多参数查询逻辑。另外多参数绑定的类型字符串需要匹配参数数量。
修改后的/class/Expenses.php:
<?php class Expenses{ private $expensesTable = "expenses"; public $id; public $month; private $amount; public $year; public function __construct($db){ $this->conn = $db; } function expenses(){ // 优先判断同时存在id和year的场景 if($this->id && $this->year) { $stmt = $this->conn->prepare("SELECT * FROM ".$this->expensesTable." WHERE id = ? AND year= ?"); // 两个整数参数,类型字符串用"ii" $stmt->bind_param("ii", $this->id, $this->year); } else 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 { $stmt = $this->conn->prepare("SELECT * FROM ".$this->expensesTable); } $stmt->execute(); $result = $stmt->get_result(); return $result; } } ?>
2. 调整readexpenses.php的参数默认值
原代码默认给id和year赋值为'0',可能导致未传参数时被误判为“有值”;同时存在变量名错误(类中定义的是$month,代码里写了$extra)。
修改后的readexpenses.php参数赋值部分:
// 默认值改为null,确保未传参数时变量判定为假 $expenses->id = (isset($_GET['id']) && $_GET['id']) ? $_GET['id'] : null; $expenses->year = (isset($_GET['year']) && $_GET['year']) ? $_GET['year'] : null; $expenses->month = (isset($_GET['month']) && $_GET['month']) ? $_GET['month'] : null; // 修正变量名错误
3. 修复.htaccess的重写规则
原规则存在重复定义,多参数正则未正确捕获第二个参数,且未添加QSA标志导致原始查询字符串被覆盖。
修改后的.htaccess:
RewriteEngine On # Turn on the rewriting engine RewriteRule ^read$ read.php [NC,L] RewriteRule ^read/([0-9_-]*)$ read.php?id=$1 [NC,L,QSA] RewriteRule ^create$ create.php [NC,L] RewriteRule ^update$ update.php [NC,L] RewriteRule ^delete$ delete.php [NC,L] RewriteRule ^expenses$ readexpenses.php [NC,L,QSA] # 支持expenses/year/xxxx格式 RewriteRule ^expenses/year/([0-9_-]*)$ readexpenses.php?year=$1 [NC,L,QSA] # 支持expenses/id/xxxx格式 RewriteRule ^expenses/id/([0-9_-]*)$ readexpenses.php?id=$1 [NC,L,QSA] # 支持expenses/id/xxxx/year/xxxx格式 RewriteRule ^expenses/id/([0-9_-]*)/year/([0-9_-]*)$ readexpenses.php?id=$1&year=$2 [NC,L,QSA]
现在测试http://localhost:8012/REST-API/items/expenses?id=2&year=2022即可正常返回符合条件的数据,单一参数、无参数请求也能正常工作。
内容的提问来源于stack exchange,提问作者carreankush
相关产品推荐
相关产品推荐

