Multiple table to encode json and display - php

Can someone help me to return JSON data with join tables? I have two tables which are sales_details and sales_payment. I want to return the data like this:
{
"sales_id":"3",
"sales_date":"2021-01-11 23:41:58",
"sales_po":"100549",
"sales_so":"1234",
"sales_dr":"5768",
"sales_si":"1794",
"sales_company":"",
"sales_cp":"",
"sales_particulars":"Authorized Personnel Only",
"sales_media":"Sticker on Sintra",
"sales_width":"16.00",
"sales_net_amount":"8601.60",
"sales_balance":"6601.60",
},
{
"payment_amount":"1000.00",
"payment_date":"2021-01-15",
"payment_remarks":""
},
{
"payment_amount":"1000.00",
"payment_date":"2021-01-18",
"payment_remarks":""
}
This what I've tried:
public function get_payment_info_by_id($payment_info_id) {
$query = $this->db->query(
"SELECT *
FROM tbl_sales_details AS tsd
INNER JOIN tbl_sales_payments AS tsp ON tsp.sales_id = tsd.sales_id
WHERE tsd.sales_id = $payment_info_id");
$jsonArray = array();
foreach($query as $row) {
$jsonArrayItem = array();
$jsonArrayItem['payment_amount'] = $row['payment_amount'];
$jsonArrayItem['payment_date'] = $row['payment_date'];
$jsonArrayItem['payment_remarks'] = $row['payment_remarks'];
array_push($jsonArray, $jsonArrayItem);
}
header('Content-type: application/json');
echo json_encode($jsonArray);
}

You can use the joined query but you must look at the result you get back and work out which parts are what you need in what part of the output
I am assuming you are using PDO and have converted the query to use perpared bound parameters.
Update Ahh I see you are using MYSQLI_ and not PDO, so I have changed the database access code. That will probably fix the undefined index errors
public function get_payment_info_by_id($payment_info_id) {
$sql = "SELECT *
FROM tbl_sales_details AS tsd
INNER JOIN tbl_sales_payments AS tsp ON tsp.sales_id = tsd.sales_id
WHERE tsd.sales_id = ?";
$stmt = $this->db->prepare($sql);
$stmt->bind_param('i', $payment_info_id);
$stmt->execute();
$result = $stmt->get_result();
$last_salesid = NULL;
$t = [];
while($row = $result->fetch_assoc()) {
if ( $last_salesid != $row['sales_id'] ) {
// get sales_details columns in this case
$t[] = [
"sales_id" => $row['sales_id'],
"sales_date" => $row['sales_date'],
"sales_po" => $row['sales_po'],
"sales_so" => $row['sales_so'],
"sales_dr" => $row['sales_dr'],
"sales_si" => $row['sales_si'],
"sales_company" => $row['sales_company'],
"sales_cp" => $row['sales_cp'],
"sales_particulars" => $row['sales_particulars'],
"sales_media" => $row['sales_media'],
"sales_width" => $row['sales_width'],
"sales_net_amount" => $row['sales_net_amount'],
"sales_balance": => $row['sales_balance']
];
$last_salesid = $row['sales_id'];
}
// then get the sales_payment info
$t[] = [
'payment_amount' => $row['payment_amount',
'payment_date'] => $row['payment_date',
'payment_remarks'] => $row['payment_remarks'
];
}
header('Content-type: application/json');
echo json_encode($t);
}

Related

PHP repeated results

I'm having hard time with this issue
I have multiple queries some data appear in other results...
$query = "SELECT * FROM `hotels`";
$result=mysqli_query($connect,$query);
if(mysqli_num_rows($result)>0) {
while($row=mysqli_fetch_array($result)) {
$hotelname = $row['hotel_name'];
$queryPhotos="SELECT * FROM hotel_photo WHERE hotel_id = ".$row['id']." ";
$resultPhotos=mysqli_query($connect,$queryPhotos);
while($rowPhotos=mysqli_fetch_assoc($resultPhotos)) {
$photos[] = array(
"imgUrl" => $rowPhotos['img_url'],
"hotel_id" => $rowPhotos['hotel_id']
);
}
$apiResult[] = array(
'hotel_name' => $hotelname,
'hotel_photos' => $photos,
);
}
header('Content-type: application/json');
echo json_encode($apiResult, JSON_NUMERIC_CHECK);
}
This is my hotel database
and my hotel_photos database
Why I'm still seeing 'hotel_id 1' in dubai hotel...?
Thank you so much for your help.
You aren't empting the $photos array in every new iteration for a new hotel. Hence, the previous results also exists in the array. You need to fix as below:
<?php
while($row = mysqli_fetch_array($result)) {
$hotelname = $row['hotel_name'];
$photos = []; // add this line

Multiple nested array from MySQL query in PHP

I'm using foreach loops to access records in a nested array.
I need to nest 3 arrays (so the first array contains an array, which also contains an array). I'm having success with 2 arrays but I can't get 3 to work.
I had my code working with 2 arrays (which worked just fine) but I can't get 3 arrays to be nested.
This is the result that I want:
[
{
"site_id": "1",
"user_plants": [
{
"user_plant_id": "1",
"site_id": "1",
"plant_id": "1",
"plant_images": [
{
"plant_image_id": "1"
},
{
"plant_image_id": "2"
},
{
"plant_image_id": "3"
},
]
}
]
}
]
My current code:
$query = "SELECT A.site_id FROM sites A WHERE A.user_id='".$user_id."' GROUP BY A.site_id";
$result = $this->conn->query($query);
$json_response = array();
$sites = array();
if ($result-> num_rows > 0) {
while ($item = $result->fetch_object())
$sites[] = $item;
foreach($sites as $item) {
$row_array = (array)$item;
$site_id = $item->site_id;
$user_plants = "SELECT A.user_plant_id, A.site_id, A.plant_id FROM user_plants A RIGHT JOIN sites B ON A.site_id ='".$site_id."'
JOIN plants C ON A.plant_id = C.plant_id GROUP BY A.user_plant_id";
$resultSet = $this->conn->query($user_plants);
$user_plants = array();
if ($resultSet-> num_rows > 0) {
while ($item = $resultSet->fetch_object())
$user_plants[] = $item;
foreach ($user_plants as $item) {
$row_array['user_plants'][] = (array)$item;
$plant_id = $item->plant_id;
$user_plant_id = $item->user_plant_id;
$plant_images = "SELECT A.plant_image_id FROM plants_images A WHERE A.plant_id ='".$plant_id."' UNION SELECT B.plant_image_id FROM user_plant_image B JOIN user_plants C ON B.user_plant_id ='".$user_plant_id."' WHERE C.user_id ='".$user_id."' GROUP BY B.plant_image_id ORDER BY plant_image_id";
$resultSet = $this->conn->query($plant_images);
$plant_images = array();
if ($resultSet->num_rows > 0) {
while ($item = $resultSet->fetch_object())
$plant_images[] = $item;
foreach ($plant_images as $item) {
$row_array['user_plants'][]['plant_images'][] = $item;
}
} else if ($resultSet->num_rows == 0) {
$row_array['plant_images'] = [];
}
}
$json_response[] = $row_array;
}
}
}
return $json_response;
The result of above code:
[
{
"site_id": "1",
"user_plants": [
{
"user_plant_id": "1",
"site_id": "1",
"plant_id": "1"
},
{
"plant_images": [
{
"plant_image_id": "1"
},
{
"plant_image_id": "2"
},
{
"plant_image_id": "3"
},
]
}
]
}
]
How should I adjust the foreach loops above to cater for this?
There's plenty of room for improvement in this code but I've ignored that and tried to keep the code matching yours in this example.
The main changes are:
Create a temporary variable $user_plant_array which we store "plant_images" against
Push that temporary variable to the $site_array at the end of the loop
Rename some loop variables to making it easier to identify what you're referencing
$json_response = array();
$sites = array();
if ($result->num_rows > 0) {
while ($site = $result->fetch_object()) {
$sites[] = $site;
}
foreach ($sites as $site) {
$site_array = (array)$site;
$site_id = $site->site_id;
$user_plants = "SELECT A.user_plant_id, A.site_id, A.plant_id FROM user_plants A RIGHT JOIN sites B ON A.site_id ='" . $site_id . "'
JOIN plants C ON A.plant_id = C.plant_id GROUP BY A.user_plant_id";
$resultSet = $this->conn->query($user_plants);
$user_plants = array();
if ($resultSet->num_rows > 0) {
while ($user_plant = $resultSet->fetch_object())
$user_plants[] = $user_plant;
foreach ($user_plants as $user_plant) {
// create a temporary variable here that we will map
// all "plant_images" to
$user_plant_array = (array)$user_plant;
$plant_id = $user_plant->plant_id;
$user_plant_id = $user_plant->user_plant_id;
$plant_images = "SELECT A.plant_image_id FROM plants_images A WHERE A.plant_id ='" . $plant_id . "' UNION SELECT B.plant_image_id FROM user_plant_image B JOIN user_plants C ON B.user_plant_id ='" . $user_plant_id . "' WHERE C.user_id ='" . $user_id . "' GROUP BY B.plant_image_id ORDER BY plant_image_id";
$resultSet = $this->conn->query($plant_images);
$plant_images = array();
if ($resultSet->num_rows > 0) {
while ($plant_image = $resultSet->fetch_object())
$plant_images[] = $plant_image;
foreach ($plant_images as $plant_image) {
$user_plant_array['plant_images'][] = $plant_image;
}
} else if ($resultSet->num_rows == 0) {
$user_plant_array['plant_images'] = [];
}
// the temporary variable now contains all "plant_images"
// now we can push that to the site array
$site_array['user_plants'][] = $user_plant_array;
}
$json_response[] = $site_array;
}
}
}
return $json_response;
Creating a separate answer as an alternate solution with some code improvements.
"Improvements" being more readability and/or more performant.
A few of the main changes I would suggest as "improvements" have been implemented in this example. The main ones being:
Using prepared SQL statements (not always required but good practice to use, especially in anything accepting user input, also can make for cleaner code)
Reducing the amount of loops (in a few places you were looping just to create an array and then looping again)
Returning/continuing early where possible (helps to prevent unnecessary nesting)
Removing unnecessary if statements (e.g. most of the while loops will be skipped if the results are empty - checking beforehand isn't entirely necessary)
More readable variable names (it's common for new coders to try and abbreviate a lot of variables and often take it too far - making them readable will save you a lot of time when debugging)
The code using mysqli might not be the best as I generally work with PDO.
function getSitesData() {
// assumes that $user_id is set somewhere before this
// assumes that $this->conn references a valid database connection
$sql = "SELECT A.site_id FROM sites A WHERE A.user_id = ? GROUP BY A.site_id";
$query = $this->conn->prepare($sql);
$query->bind_param("i", $user_id);
$query->execute();
$site_result = $query->get_result();
$sites = [];
while ($site = $site_result->fetch_assoc()) {
// using fetch_assoc gives us an associative array
// initialise empty array
$site["user_plants"] = [];
// get user_plants
$sql = "SELECT A.user_plant_id, A.site_id, A.plant_id FROM user_plants A RIGHT JOIN sites B ON A.site_id = ?
JOIN plants C ON A.plant_id = C.plant_id GROUP BY A.user_plant_id";
$query = $this->conn->prepare($sql);
$query->bind_param("i", $site["site_id"]);
$query->execute();
$user_plant_result = $query->get_result();
while ($user_plant = $user_plant_result->fetch_assoc()) {
// intialise empty array
$user_plant["plant_images"] = [];
// get plant images
$sql = "SELECT A.plant_image_id FROM plants_images A WHERE A.plant_id = ? UNION SELECT B.plant_image_id FROM user_plant_image B JOIN user_plants C ON B.user_plant_id = ? WHERE C.user_id = ? GROUP BY B.plant_image_id ORDER BY plant_image_id";
$query = $this->conn->prepare($sql);
$query->bind_param("iii", $user_plant["plant_id"], $user_plant["user_plant_id"], $user_id);
$query->execute();
$plant_image_result = $query->get_result();
while ($plant_image = $plant_image_result->fetch_assoc()) {
$user_plant["plant_images"][] = $plant_image;
}
$sites["user_plants"][] = $user_plant;
}
$sites[] = $site;
}
return $sites;
}

Echo nested JSON array from related database tables with a single query?

I have two database tables that contain information about land contracts. They are related with land_contract_annual_price.land_contract_id -> land_contract.land_contract_id.
Table 'land_contract'
Table 'land_contract_annual_price'
If a land contract has the value "Rörligt pris" in the field land_contract_price_type, there are related values in the table
land_contract_annual_price. At the moment I'm doing two queries, one to each table. I then merge the results and present the land contract as a nested JSON array like this:
Version 1
[
{
"land_contract_id":118,
"land_contract_name":"Avtalsnamn",
"location_id":71,
"land_contract_link":"",
"land_contract_notes":"",
"land_owner_id":2,
"land_contract_start_date":"2019-07-25",
"land_contract_end_date":"2023-07-25",
"land_contract_terminated":"false",
"land_contract_payment_interval":"Halv\u00e5rsvis",
"land_contract_price_type":"R\u00f6rligt \u00e5rspris",
"land_contract_fixed_annual_price":null,
"land_contract_annual_prices":[
{"year":1, "price":873.00},
{"year":2, "price":77289.00},
{"year":3, "price":8.00},
{"year":4, "price":0.00},
{"year":5, "price":8729.00}
]
}
]
If a land contract has the value "Fast pris" in the field land_contract_price_type, there are no related values in the table
land_contract_annual_price. In that case I present the land contract like this (without the extra array at the end):
Version 2
[
{
"land_contract_id":13,
"land_contract_name":null,
"location_id":null,
"land_contract_link":"https:\/\/www.something.com\/preview\/Sl%C3%A4pvdam%20Edda\/Kddal\/Bddkta\/Besika%20Markavtal%20%20Halmstad%202016-03-08.pdf?role=personal",
"land_contract_notes":"",
"land_owner_id":null,
"land_contract_start_date":"2016-03-08",
"land_contract_end_date":"2026-03-08",
"land_contract_terminated":"true",
"land_contract_payment_interval":"\u00c5rsvis",
"land_contract_price_type":"Fast \u00e5rspris",
"land_contract_fixed_annual_price":"6000.00"
}
]
What I didn't think of, is that this solution is bad when I'm fetchin ALL the land contracts. If I'm going to do a second query to another table whenever a land contract has the value "Rörligt pris" in the field land_contract_price_type, I'm going to do hundreds of extra queries.
Is there a way to create the nested JSON array with one (1) query when a land contract has the value "Rörligt pris" in the field land_contract_price_type?
Thanks!
Below is my current code.
function read($pdo, $Id = null, $ResponseMessage = null) {
$params = [];
$array = [];
$sql = "SELECT lc.Id, lc.Name, lc.LocationId, l.Name AS LocationName, lc.Notes, lc.LandOwnerId, lo.Name AS LandOwnerName, lc.StartDate, lc.EndDate, lc.IsTerminated, lc.PaymentInterval, lc.PriceType, lc.FixedAnnualPrice, lc.Link, lc.Created, lc.Updated, lcap.AnnualPriceYear AS Year, lcap.AnnualPriceAmount AS Amount
FROM LandContract lc
LEFT JOIN Location l ON l.Id = lc.LocationId
LEFT JOIN LandOwner lo ON lo.Id = lc.LandOwnerId
LEFT JOIN LandContractAnnualPrice lcap ON lcap.LandContractId = lc.Id
ORDER BY lc.Id DESC, lcap.AnnualPriceYear DESC
";
if ($Id) {
$sql .= 'WHERE lc.Id = ?';
$params[] = $Id;
}
echo $sql;
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
while ($row = $stmt->fetch()) {
// Fields we want to extract from the select statement into the array
$select_fields = ['Id', 'Name', 'LocationId', 'LocationName', 'Link', 'Notes', 'LandOwnerId', 'LandOwnerName',
'StartDate', 'EndDate', 'IsTerminated', 'PaymentInterval',
'PriceType', 'FixedAnnualPrice ', 'Created', 'Updated'];
if (!isset($array[$row['Id']])) {
// initialize the subarray if it has not been set already
$array[$row['Id']] = array_intersect_key($row, array_flip($select_fields));
if ($row['Year'] != null) {
$array[$row['Id']]['AnnualPrices'] = [];
} else {
$array[$row['Id']]['AnnualPrice'] = $row['FixedAnnualPrice'];
}
}
if ($row['Year'] != null) {
$array[$row['Id']]['AnnualPrices'][] = ['Year' => $row['Year'], 'Amount' => $row['Amount']];
}
}
if (empty($array)) {
$ResponseMessage = new ResponseMessage();
$ResponseMessage->Status = 'Error';
$ResponseMessage->Message = 'No results';
echo json_encode($ResponseMessage, JSON_UNESCAPED_UNICODE);
exit;
}
$Response = array();
if ($ResponseMessage) {
$Response['Status'] = $ResponseMessage->Status;
$Response['Message'] = $ResponseMessage->Message;
}
$Response['LandContracts'] = array_values($array);
echo json_encode($Response, JSON_UNESCAPED_UNICODE);
$stmt = null;
}
You are better off using a JOIN query, and then structure your array from the result - having a query within a loop is often a very bad idea, and an indicator that you can use a JOIN instead.
You want to use a LEFT JOIN, joining them on the land_contract_id in both tables.
Then loop your results, and construct your array, which you can end up encoding into a JSON string once done.
$params = [];
$array = [];
$sql = "SELECT lc.*,
py.land_contract_annual_price_year AS `year`,
py.land_contract_annual_price_amount AS `amount`
FROM land_contract AS lc
LEFT JOIN land_contract_annual_price AS py
ON py.land_contract_id = lc.land_contract_id
";
if (isset($_POST['land_contract_id'])) {
$sql .= 'WHERE lc.land_contract_id = ?';
$params[] = $_POST["land_contract_id"];
}
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
while ($row = $stmt->fetch()) {
// Fields we want to extract from the select statement into the array
$select_fields = ['land_contract_id', 'land_contract_name', 'location_id', 'land_contract_link', 'land_contract_notes', 'land_owner_id',
'land_contract_start_date', 'land_contract_end_date', 'land_contract_terminated', 'land_contract_payment_interval',
'land_contract_price_type', 'land_contract_fixed_annual_price '];
if (!isset($array[$row['land_contract_id']])) {
// initialize the subarray if it has not been set already
$array[$row['land_contract_id']] = array_intersect_key($row, array_flip($select_fields));
if ($row['year'] != null) {
$array[$row['land_contract_id']]['land_contract_annual_prices'] = [];
} else {
$array[$row['land_contract_id']]['land_contract_annual_price'] = $row['land_contract_fixed_annual_price'];
}
}
if ($row['year'] != null) {
$array[$row['land_contract_id']]['land_contract_annual_prices'][] = ['year' => $row['year'], 'amount' => $row['amount']];
}
}
if (empty($array)) {
echo "No results";
exit;
}
echo json_encode($array, JSON_UNESCAPED_UNICODE);

How to save for loop inside while loop variable in PHP

I'm really having a hard time to save this loop of mine in my system i need to ask if how many style they need for example they chose 3.. there's 3 table will appear and each table you need to write in quantity..
In my saving here's my codes
$numgen = $_POST['numgen']; //number of style (i chose 3 style)
$x= 1;
while($x <= $numgen)
{
$elements = array();
foreach ($_POST['barcode'.$x] as $barcode)
{
$stmt = $db->prepare("SELECT * FROM productmaterialnumber where materialnumber = :bid");
$stmt->execute(array(':bid' => $barcode)) or die(print_r($db->errorInfo(), true));
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$productmaterialnumberID = $row['productmaterialnumberID'];
$matnum = $row['materialnumber'.$x];
$color = $row['color'];
$size = $row['size'];
$productgenericnumberID = $row['productgenericnumberID'];
$productstylecodeID = $row['productstylecodeID'];
$qty = $_POST[$matnum];
$totalqty += $qty;
$matnummm[] = $matnum."<br>";
$quantttt[] = $qty."<br>";
$sizzeeee[] = $size."<br>";
$colooor[] = $color."<br>";
}
$stmt = $db->prepare("INSERT INTO barcoderequest(reqID, buyerID, qty, materialnumber, ID, printstatus, division,
purrequest, dateadded, vendorID, remarks)
VALUES(:field0, :field1, :field2, :field3, :field4, :field5, :field6, :field7, :field8, :field9, :field10)");
$stmt->execute(array(':field0' => $defaultreqnum, ':field1' => $userID,
':field2' => $qty, ':field3' => $matnum, ':field4' => $ID, ':field5' => "Pending", ':field6' => $gennum.$division,
':field7' =>"Pending", ':field8' =>$currentdatetime, ':field9' => $vendor, ':field10' => $remarks))
or die(print_r($db->errorInfo(), true));
}
$x++;
}
If you notice i inserted $x beside $POST['barcode'.$x] $matnum = $row['materialnumber'.$x] so i can know the id but its not working but when i remove the $x it saves 3 times since i choose 3 style.
Can someone help me? THanks
$_POST['barcode'.$x] => not a collection so you cant loop over it.
Try this:
<?php
$_POST['numgen'] = 3;//For testing only (Needs to be removed!)
$numgen = $_POST['numgen'];
$_POST["barcode1"] = "1234566789"; //For testing only (Needs to be removed!)
$_POST["barcode2"] = "987654321"; //For testing only (Needs to be removed!)
$_POST["barcode3"] = "147852369"; //For testing only (Needs to be removed!)
$x= 1;
while($x <= $numgen)
{
foreach ($_POST as $key => $value) { //Loop over post instead of individual barcodes
$x="";
$barcode="";
if (strstr($key, 'barcode')) {
$x = str_replace('barcode', '', $key); //Get barcode number
$barcode = $value; // Get barcode
}
if ( $barcode != "") {
echo "Barcode".$x." :".$barcode."<br/>";//For testing only (Needs to be removed!)
$stmt = $db->prepare("SELECT * FROM productmaterialnumber where materialnumber = :bid");
$stmt->execute(array(':bid' => $barcode)) or die(print_r($db->errorInfo(), true));
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$productmaterialnumberID = $row['productmaterialnumberID'];
$matnum = $row['materialnumber'.$x];
$color = $row['color'];
$size = $row['size'];
$productgenericnumberID = $row['productgenericnumberID'];
$productstylecodeID = $row['productstylecodeID'];
$qty = $_POST[$matnum];
$totalqty += $qty;
$matnummm[] = $matnum."<br>";
$quantttt[] = $qty."<br>";
$sizzeeee[] = $size."<br>";
$colooor[] = $color."<br>";
}
$stmt = $db->prepare("INSERT INTO barcoderequest(reqID, buyerID, qty, materialnumber, ID, printstatus, division,
purrequest, dateadded, vendorID, remarks)
VALUES(:field0, :field1, :field2, :field3, :field4, :field5, :field6, :field7, :field8, :field9, :field10)");
$stmt->execute(array(':field0' => $defaultreqnum, ':field1' => $userID,
':field2' => $qty, ':field3' => $matnum, ':field4' => $ID, ':field5' => "Pending", ':field6' => $gennum.$division,
':field7' =>"Pending", ':field8' =>$currentdatetime, ':field9' => $vendor, ':field10' => $remarks))
or die(print_r($db->errorInfo(), true));
$x++;
}
}
}
?>

How to grab an array from a query

I have a function getCart which has a complicated query that is merged together. I want to select only one array that is $cart['tee_times'] = array(); and place that array in another function. How can I accomplish this?
Here is a snippet of the query I am trying to pull from.
function getCart($id, DBConnection $connection) {
$query = 'SELECT * FROM cart WHERE IDCart=:cart_id LIMIT 1';
$prepared = array(
"cart_id" => $id
);
$results = $connection->fetch($query, $prepared);
$cart = !empty($results) ? $results[0] : null;
if (isset($cart)) {
$cart['IDCustomer'] = isset($cart['IDCustomer']) ? (int)$cart['IDCustomer'] : null;
$cart['IDDestination'] = isset($cart['IDDestination']) ? (int)$cart['IDDestination'] : null;
$cart['total'] = 0;
$cart['tee_times'] = array();
$cart['rooms'] = array();
$cart['cars'] = array();
$query = '
SELECT
a.*,
e. city_name,
f.IDDestination,
((CASE DATE_FORMAT(a.teetime_dt, "%w")
WHEN 0 THEN b.sun
WHEN 1 THEN b.mon
WHEN 2 THEN b.tue
WHEN 3 THEN b.wed
WHEN 4 THEN b.thu
WHEN 5 THEN b.fri
WHEN 6 THEN b.sat
ELSE 0
END) * a.no_rounds * a.no_golfers) price,
c.tax_rate
FROM cart_course_teetimes a
JOIN course_priceplan b
ON b.IDCoursePricePlan = a.IDCoursePricePlan
JOIN course_tax c
ON c.IDCourseTax = a.IDCourseTax
JOIN course d
ON d.IDCourse = b. IDCourse
JOIN vw_cities e
ON e.IDCity = d. IDCity
JOIN destinations_cities f
ON f.IDCity = e.IDCity
WHERE IDCart=:cart_id
';
$results = $connection->fetch($query, $prepared);
foreach ($results as $row) {
$formatted = array(
'IDCartTeetimes' => (int)$row['IDCartTeetimes'],
'IDCoursePricePlan' => (int)$row['IDCoursePricePlan'],
'IDCourseTax' => (int)$row['IDCourseTax'],
'teetime_date' => $row['teetime_dt'],
'num_golfers' => (int)$row['no_golfers'],
'num_rounds' => (int)$row['no_rounds'],
'price' => (float)$row['price'],
'tax_rate' => (float)$row['tax_rate'],
'city_name' => $row['city_name'],
'IDDestination' => (int)$row['IDDestination'],
);
$cart['tee_times'][] = $formatted;
$cart['total'] += $formatted['price'];
}
Here is my function and my attempt at retrieving the tee_times array
function filterCart($cart_id, DBConnection $connection) {
$cart = getCart($cart_id, $connection);
if (!isset($cart)) {
http_response_code(404);
return 'Cart does not exist.';
}
$results =$cart['tee_times'];
echo $results;
$id = null;
foreach ($results as $row){
var_dump($row['IDDestination']);
If you want to filter out courses that have more than one IDDestination, change the WHERE clause to:
WHERE IDCart = :cart_id
AND IDCart NOT IN (
SELECT IDCart
FROM course a
JOIN destinations_cities b ON b.IDCity = a.IDCity
GROUP BY IDCart
HAVING COUNT(*) > 1)

Categories