0

I'm having trouble figuring out how to pass the database connection $db = establish_connection() into the sql query in the calculateOrderAmount() function. I'm novice to php and and getting comfused how to resolve this issue. Here is the code:

include 'common.php';

global $db;
$db = establish_database();
$price = 0;

//Need to throw error if service not found
function calculateOrderAmount(array $items): int {
    foreach ($items as $key => $value){
        switch($key) {
            case "service": $service = $value; break;
            case "duration": $duration = $value; break;
            case "people" : $people = $value; break;
        }
    }
    
    $serviceDetails = $db->query("SELECT * FROM services WHERE service=\"" . $service . "\";");
            foreach ($serviceDetails as $row) {
                $cost = $row["cost"];
                $wage = $row["wage"];
            }
    if (wage == "per"){
        $price = $people * $cost;
    }else if (duration != 8){
        $price = $people * $cost * $duration;
    }else{
        $price = $cost;
    }
    
  return $price;
}
    header('Content-Type: application/json');
    try {  
      // retrieve JSON from POST body
      $json_str = file_get_contents('php://input');
      $json_obj = json_decode($json_str);
      $paymentIntent = \Stripe\PaymentIntent::create([
        'amount' => calculateOrderAmount($json_obj->items),
        'currency' => 'usd',
      ]);
      $output = [
        'clientSecret' => $paymentIntent->client_secret,
      ];
      echo json_encode($output);
    } catch (Error $e) {
      http_response_code(500);
      echo json_encode(['error' => $e->getMessage()]);
    }

I'm getting the error "PHP Notice: Undefined variable: db." Also, the error "client.js:616 POST payment.php 500" in the console. Thanks!

0 Answers0