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!

4
  • Yes, it worked! Thank you! Commented Jul 27, 2020 at 5:44
  • Using global should be avoided as much as possible. It's easy enough to use function calculateOrderAmount(array $items, $db) (You can add whatever database type it is) and call with calculateOrderAmount($json_obj->items, $db) Commented Jul 27, 2020 at 5:54
  • How do I know what type of database it is? Commented Jul 27, 2020 at 5:57
  • probably - \PDO, or \mysqli Commented Jul 27, 2020 at 5:59

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.