search

Home  >  Q&A  >  body text

Create REST API GET method with multiple filters in PHP

I created a REST API GET method in php using parameter id. http://localhost:8012/REST-API/items/expenses?id=2. This works fine, but I want to use http://localhost:8012/REST-API/items/expenses?id=2&year=2022 to get the data. I am new to php and tried all possibilities but not getting the correct response. Below is the code

Expenses.php

in

/class file
<?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; 
    }
}
?>

readexpenses.php

<?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.")
    );
}

.htaccess

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]

P粉937769356P粉937769356305 days ago386

reply all(1)I'll reply

  • P粉642919823

    P粉6429198232024-01-30 00:37:39

    As I said in the comments, his last three rules are wrong:

    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]

    What will happen to this URL? http://example.com/expenses/2012 How to detect if this is id or year?

    I recommend using this solution:

    http://example.com/expenses/id/2012   -> readexpenses.php?id=2012
    http://example.com/expenses/year/2022 -> readexpenses.php?year=2022
    http://example.com/expenses/2012/2022 -> readexpenses.php?id=2012&year=2022

    So the .htaccess file will be: (just changed the last three rules)

    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/year/([0-9]+)$ readexpenses.php?year= [NC,L]
    RewriteRule ^expenses/id/([0-9]+)$ readexpenses.php?id= [NC,L]
    RewriteRule ^expenses/([0-9]+)/([0-9]+)$ readexpenses.php?id=&year= [NC,L]

    online test:

    I have tested this and it works in all cases id/year , id< /code> and Year , below you can see it passes the url

    You should also change your php conditions

    if ($this->id && $this->year) {
      //..
    } else if ($this->id) {
      //..
    } else if ($this->year) {
      //..
    } else {
      //..
    }

    Without this change it would never reach the time set by the id and year

    reply
    0
  • Cancelreply