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);
Related
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;
}
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);
}
The DB stores several accounts: [winnie, winnie9, winnie10], however the query only returns one record when I fetch the data. What would be the solution?
Model method:
protected function getApprovedUsers($login) {
$sql = "SELECT `email`, `login`, `name`, `reg_date`, `pass`, `role` FROM `approved` WHERE `login` LIKE ?";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$login]);
if($users = $stmt->fetchAll())
return $users;
return null;
}
Controller call to the Model:
public function getCertainApprovedUser($login) {
$users = $this->getApprovedUsers($login);
if(is_array($users) || is_object($users)) {
foreach ($users as $user) {
return array("email"=>$user["email"], "login"=>$user["login"], "pass"=> $user["pass"],
"name"=> $user["name"], "reg_date"=> $user["reg_date"], "role"=> $user["role"]);
}
}
else {
throw new Exception("Nothing to fetch");
}
}
}
Processing the data so that LIKE statement would work properly (%%):
$record = $userContr->getCertainApprovedUser("%$login%");
$someJSON = array(
[
"login"=>"{$record['login']}",
"email"=>"{$record['email']}",
"name"=>"{$record['name']}",
"reg_date"=>"{$record['reg_date']}"
]
);
$newJSON = json_encode($someJSON);
echo $newJSON;
in the method getCertainApprovedUser(), you are returning a value in the foreach. This breaks immediatly the loop at the first iteration.
Changes your loop to something like :
$result = []; // initialize an empty array
foreach ($users as $user) {
// add a user to that array
$result[] = array("email"=>$user["email"], "login"=>$user["login"], "pass"=> $user["pass"], "name"=> $user["name"], "reg_date"=> $user["reg_date"], "role"=> $user["role"]);
}
// return the array containing the users
return $result;
And then, to build your json, apply the same logic :
$someJSON = [];
foreach ($record as $user)
{
$someJSON[] = [
"login"=>$user['login'],
"email"=>$user['email'],
"name"=>$user['name'],
"reg_date"=>$user['reg_date']
];
}
I have two tables sport_tbl, match_tbl. In sport_tbl, i defined sport_name such as cricket. In match_tbl, I have match_name,match_date,sport_id.
I want to show match_date of every sport_name (ex. i am showing match_date list for cricket sport and i want to show every date has match_name list).
I want to show one distinct match_date.
Image
my controller code:-
$url = 'cricket' // for example first sport_name
$data['getSportMatch'] = $this->user_model->getSportMatch($url);
my model code:-
public function getSportMatch($sport)
{
$query = $this->db->get_where('match_tbl',array('sport_name' => $sport));
if($query->num_rows > 0)
{
foreach($query->result() as $item){
$data[] = $item;
}
return $data;
}
}
my code in view:-
<div><?php foreach($getSport as $item): ?><h4><?= $item->sport_name; ?></h4><div><?= foreach($getSportMatch as $item): ?>
match_date)) ?>here i want to show list match_name of every match_date
My table structure images
1) sport_tbl
2) match_tbl
3) another match_tbl
you can solve this in model easily. if i did not understand wrong . you need 2 function in model.
1. will get sport names
2. will get matches of given sport name
//model functions
function get_sports(){
$data = array();
$sports = $this->db->select('sport_name')->from('sport_tbl')->get()->result();
if($sports)
{
foreach($sports as $sport){
$data[$sport->sport_name] = $this->get_matches($sport->sport_name);
}
return $data;
}
}
function get_matches($sport_name){
$matches = $this->db->select('*')->from('match_tbl')->where('sport_name',$sport_name)->get()->result();
return $matches;
}
so in view data will be something like this
$data => array(
'cricket'=> array(0 => array(
'match_id' => 11,
'sport_id' = 2 .....
)))
Try this coding ...
public function getSportMatch($sport)
{
$query = $this->db->query("SELECT * FROM sport_tbl as st INNER JOIN match_tbl as mt ON st.sport_id = mt.sport_id WHERE st.sport_name ='".$sport."'");
if($query->num_rows > 0)
{
$query_result = $query->result_array();
$final_result = array();
foreach($query_result as $result ) {
$date = $result['match_date'];
$final_result[$date][] = $result;
}
return $final_result;
}
}
View Coding :-
if(isset($final_result)) {
foreach($final_result as $result) {
echo $result['match_date']; // First display match date
if(isset($result['match_date'])) {
foreach($result['match_date'] as $match) {
echo $match['match_name']; // Second listout the match name
}
}
}
}
I want to fetch contents with multiple filters, right now there's only one.
For Example:
SELECT * FROM Table1 WHERE status=true AND category = 'Camera' AND
model = 'Samsung' AND type = 'New'
I want to create an array for it. But as I'm a newbie in this one not getting a lead.
function getAllRequests($filter){
if(empty($filter)){
$addfilter = '';
}else{
$addfilter = 'AND cat_id=' . $filter;
}
}
$sql = 'SELECT * FROM Table1 WHERE status=true' . $filter;
Any help will be appreciated.
This will get you closer to the solution, though it will not replace the cat_id in the query, which will certainly be wrong - though impossible to do too much more without the array structure:
function getAllRequests($filter)
{
$addfilter="";
if(!empty($filter))
{
foreach($filter as $val)
{
$addfilter. = ' AND cat_id=' . $val .'\'';
}
}
return $addFilter;
}
$myFilters=getAllRequests($filter);
$sql = 'SELECT * FROM Table1 WHERE status=true' . $myFilters;
On the other hand, if your array is strucutred in a way like this:
array{ category => camera, model => samsung); // etc
you could use the following:
function getAllRequests($filter)
{
$addfilter="";
if(!empty($filter))
{
foreach($filter as $key => $val)
{
$addfilter. = " AND `$key` = '$val'";
}
}
return $addFilter;
}
$myFilters=getAllRequests($filter);
$sql = 'SELECT * FROM Table1 WHERE status=true' . $myFilters;
Edit: You can loop through all the filters in the following manner:
function getAllRequests()
{
$addfilter="";
if(!empty($_REQUEST))
{
foreach($_REQUEST as $key => $val)
{
$addfilter. = " AND `$key` = '$val'";
}
}
return $addFilter;
}
$myFilters=getAllRequests();
$sql = 'SELECT * FROM Table1 WHERE status=true' . $myFilters;
You don't need to pass the $_REQUEST (which will work for both GET and POST) as it already a superglobal.
function getAllRequests($filter){
if(empty($filter)){
$addfilter = '';
}else{
$addfilter = 'AND cat_id=' . $filter;
}
}
$sql = 'SELECT * FROM Table1 WHERE status=true' . $addfilter;
You can use another approach, which is using optional parameters and it will make your WHERE clause dynamic as you want. In this approach you pass all parameters' values directly to the sql query which should look like so:
SELECT *
FROM Table1
WHERE 1 = 1
AND (#status IS NULL OR status = #statusParam)
AND (#category IS NULL OR category = #categoryParam)
AND (#model IS NULL OR model = #modelParam)
AND (#type IS NULL OR type = #typeParam)
Then If any of the parameters #statusParam, #categoryParam, #modelParam or #typeParam passed to the query with NULL values, then the comparison with the column holding that value will be ignored. I used the predicate 1 = 1, in case all the values passed to the query with all NULL values in the case all the WHERE clause will be ignored as it won't presented, since WHERE 1 = 1 always true and it will be like SELECT * FROM Table1.
use this
function getAllRequests($filter){
if(empty($filter)){
$addfilter = '';
}else{
$addfilter .= 'AND cat_id=' . $filter;
}
return $addfilter;
}
$sql = 'SELECT * FROM Table1 WHERE status=true' . getAllRequests($filter);
When you are sending array make sure it has indexes
$conditions = array('category' => 'Camera', 'model' => 'Samsung' , 'type' => 'New')
Now loop through it. in your else condition
foreach($conditions as $key =>$value){
$addfilter .= 'AND ' . $key . ' = ' . $value;
}