CameraBuy / web / api / elementinformation.php
elementinformation.php
Raw
<?php
#       This script can be requested to get information about any element or product
#       it will always return all of the information about an entry if requested, this way it can be assured that the request answer can information about an element
#       The file is requested via a POST request and expects json data, it also returns the answer in json format
#       request this file with the following body: {elementid = ID}
#       only request one element at a time
#       there are special requests, that overwrite the request
####
####    special request:                result:
####                total                   total price of the cart
####


if (! $_SERVER['REQUEST_METHOD'] === 'POST') {
    exit("not permitted bad request");
}

//getting the request data
$requestData = json_decode(file_get_contents('php://input'), true);



// connecting to the db
$servername = "10.80.0.11";
$username = "root";
$password = "cr4ftd4t4b4s3";
$dbname = "craftdb";
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo(json_encode("DB ERROR $e"));
}

if (isset($requestData["total"])) {
    session_start();
    $result = 0;
    if (count($_SESSION["cart"]) != []) {
        foreach ($_SESSION["cart"] as $item => $count) {
            $stmt = $conn->prepare("SELECT field_price_ybeavgky as price
                                    FROM content
                                    WHERE id = :id");
            $stmt->bindParam(':id', $item, PDO::PARAM_INT);
            $stmt->execute();
            $itemprice = $stmt->fetch(PDO::FETCH_ASSOC);
            $result += ($itemprice["price"] * $count);
        }
    }else $result = 0;

}elseif(isset($requestData["elementid"])){
    $id = $requestData["elementid"];
        $stmt = $conn->prepare("SELECT *
                                FROM content
                                WHERE id = :id");
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        // Clean the data by encoding non-empty values to UTF-8
        $result = array_map(function ($value) {
        return is_string($value) ? utf8_encode($value) : $value;
        }, $result);
}



// Convert the result to JSON
$jsonResult = json_encode($result);

// Check for JSON encoding errors
if ($jsonResult === false) {
    throw new RuntimeException('JSON encoding error: ' . json_last_error_msg());
}

// Output the JSON result
header('Content-Type: application/json');
echo $jsonResult;


?>