Home > Software design >  Pass parameter from URL to a php function in an api php
Pass parameter from URL to a php function in an api php

Time:10-19

I have a working API written in PHP, my code works fine but I need to pass a parameters to the API. but it is not working as expected. In my readOrders function, I am getting all the orders, but now I want to get all orders with ids above a particular number passed on from the url accessing the api.

 function getOrders($last_oid){
 $stmt = $this->con->prepare("SELECT oid, uid, order_num, create_date, status_date FROM orders WHERE oid > ?");
 $stmt->execute($last_oid);
 $stmt->bind_result($oid, $uid, $order_num, $create_date, $status_date);
 
 $orders = array(); 
 
 while($stmt->fetch()){
 $order  = array();
 $order['oid'] = $oid; 
 $order['uid'] = $uid; 
 $order['order_num'] = $order_num; 
 $order['create_date'] = $create_date; 
 $order['status_date'] = $status_date; 
 
 array_push($orders, $order); 
 }
 
 return $orders; 
 }

I was getting all the orders when I didn't have a parameter $last_oid. that parameter is to fetch orders with id WHERE id>? and pass the last_id in execute().

And in my API call, I am passing the last_id, it is currently hard coded, after I am done I will use $_GET to get the value and pass it to the function.

 //the READ operation
 //if the call is get orders
 case 'getOrders':
 $db = new DbOperation();
 $response['error'] = false; 
 $response['message'] = 'Request orders successfully completed';
 $response['orders'] = $db->getOrders(504);
 break; 

I am not sure what I am not doing right. I am getting an empty json but I could should be getting some few rows.

CodePudding user response:

You have an error in the code. You are executing a "prepared statement" but with the wrong statements. Try it like this:

function getOrders($last_oid)
{
   try {
      $orders = array();
      $stmt = $this->con->prepare("SELECT oid, uid, order_num, create_date, status_date FROM orders WHERE oid > ?");
      // I assume $ last_oid is an integer.
      $stmt->bind_param("i", $last_oid);
      if ($stmt->execute()) {
         $result = $stmt->get_result();

         // use the while loop to load the result set
         while ($row = $result->fetch_assoc()) {
            array_push($orders, array(
               'oid' => $row['oid'],
               'uid' => $row['uid'],
               'order_num' => $row['order_num'],
               'create_date' => $row['create_date'],
               'status_date' => $row['status_date']
            ));  
         } 
         return $orders;
      } 

   } catch (Exception $ex) {
      print $ex->getMessage();
   }
}
  • Related