How to grab an array from a query - php

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)

Related

Multiple table to encode json and display

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);
}

Error coming when table is empty in mysql, How to solve?

I have query in php
select
c.*,
CONCAT(c.first_name, ' ' ,c.middle_name, ' ' ,c.last_name) as name,
r.paid_amount as total_amount_paid,
r.emi_date as emi_date_from_reciept,
ltc.loan_amount as total_remaining_loan_amount ,
ltc.emi_date as emi_loan_date,
ltc.no_of_month as num_of_months_from_ltc
FROM loan_to_customer ltc
LEFT JOIN customer c ON ltc.customer_id = c.customer_id
LEFT JOIN receipt r ON r.customer_id = c.customer_id
WHERE c.cust_mobile = '$cust_mobile' OR c.unique_no = '$unique_no'
I am getting this error
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1`
I am getting this error while my table is empty.
If I execute this on phpmyadmin it simply run and success.
My php code is like this
<?php
include "connection.php";
extract($_REQUEST);
$data = array();
$resArr = array();
$query = customSelectQuery("select c.*, CONCAT(c.first_name, ' ' ,c.middle_name, ' ' ,c.last_name) as name,r.paid_amount as total_amount_paid,
r.emi_date as emi_date_from_reciept, ltc.loan_amount as total_remaining_loan_amount ,
ltc.emi_date as emi_loan_date, ltc.no_of_month as num_of_months_from_ltc FROM loan_to_customer ltc
LEFT JOIN customer c ON ltc.customer_id = c.customer_id
LEFT JOIN receipt r ON r.customer_id = c.customer_id
WHERE c.cust_mobile = '$cust_mobile' OR c.unique_no = '$unique_no'");
if (isset($query)) {
$ltc_data = array();
foreach ($query as $row) {
$ltc_data = array(
'loan_amount' => $row['loan_amount'],
'total_remaining_loan_amount' => $row['total_remaining_loan_amount'],
'no_of_month' => $row['no_of_month'],
"num_of_months_from_ltc"=>$row['num_of_months_from_ltc'],
"emi_date_from_reciept" => $row['emi_date_from_reciept'],
"customer_id"=>$row['customer_id'],
);
}
}
$customer_id = $ltc_data['customer_id'];
$query1 = customSelectQuery("SELECT * FROM receipt WHERE customer_id = $customer_id");
$penalty_amoount = '100';
$paid_emi_date = array();
foreach ($query1 as $row1) {
$paid_emi_date[] = array('date'=>$row1['emi_date'],'amount'=>$row1['paid_amount'], 'penalty_amoount'=>$penalty_amoount);
}
$loan_amount = $ltc_data['loan_amount'];
$total_remaining_loan_amount = $ltc_data['total_remaining_loan_amount'];
$total_amount_paid = $loan_amount - $total_remaining_loan_amount;
$no_of_month = $ltc_data['no_of_month'];
$num_of_months_from_ltc = $ltc_data['num_of_months_from_ltc'];
$total_paid_emi_month = $no_of_month - $num_of_months_from_ltc;
$penalty_amoount1 = '20';
if (sizeOf($query) > 0) {
$d = array();
foreach ($query as $row) {
// $output = [];
foreach ( explode(',', $row['emi_loan_date']) as $date ) {
$output[] = ['date' => $date, 'emi_amount' => $row['emi_amount'], 'penalty_amoount'=>$penalty_amoount1];
}
$emi_date1 = $output[0]['date'];
$emi_a = $output[0]['emi_amount'];
$p_amo = $output[0]['penalty_amoount'];
$f_a = $emi_a + $p_amo;
$d[] = array(
"name" => $row['name'],
"Loan_Account_No" => $row['unique_no'],
"product_amount"=> $row['product_amount'],
"num_of_months" => $row['num_of_months'],
"no_of_month" => $no_of_month,
"loan_amount" => $row['loan_amount'],
"total_paid_emi_month" =>$total_paid_emi_month,
'total_amount_paid' => $total_amount_paid,
'total_remaining_loan_amount' => $row['total_remaining_loan_amount'],
"pending_emi_amount"=>$f_a,
"pending_emi_date"=>$emi_date1,
// "emi_date1" => explode(',', $row['emi_loan_date']),
"emi_date1" =>$output,
"paid_emi_date"=> $paid_emi_date,
"start_emi_date"=> $row['loan_date'],
"emi_amount"=> $row['emi_amount'],
// "emi_pending_amount"=>
);
}
}
if($d === null){
$d = " ";
$message = "not found loan data.";
}
$resArr = array("success" => 1, "data" => $d, "message" => $message);
header('Content-Type: application/json');
echo str_replace("\/", "/", json_encode($resArr, JSON_UNESCAPED_UNICODE));
?>
replace '$cust_mobile' by '\''.$cust_mobile.'\'' and '$unique_no' by '\''.$unique_no.'\''. Because $cust_mobile and $unique_no are variables
select c.*, CONCAT(c.first_name, ' ' ,c.middle_name, ' ' ,c.last_name) as name,r.paid_amount as total_amount_paid,
r.emi_date as emi_date_from_reciept, ltc.loan_amount as total_remaining_loan_amount ,
ltc.emi_date as emi_loan_date, ltc.no_of_month as num_of_months_from_ltc FROM loan_to_customer ltc
LEFT JOIN customer c ON ltc.customer_id = c.customer_id
LEFT JOIN receipt r ON r.customer_id = c.customer_id
WHERE c.cust_mobile = '\''.$cust_mobile.'\'' OR c.unique_no = '\''.$unique_no.'\''

Refactor if statements in PHP or another solution for if statements (not switch case)

I have some if statements in my code.
e.g:
if($option[0]->posts == 1 && $option[0]->pages == 1){
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND (post_type="page" OR post_type="post") ORDER BY post_title ASC', OBJECT );
}
if($option[0]->pages == 1 && $option[0]->posts == 0){
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND post_type="page" ORDER BY post_title ASC', OBJECT );
}
if($option[0]->pages == 0 && $option[0]->posts == 1){
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND post_type="post" ORDER BY post_title ASC', OBJECT );
}
a bit pseudo code of the code above:
if foo = 1 and bar = 1 -> return foo and bar
if foo = 0 and bar = 1 -> return only bar
if foo = 1 and bar = 0 -> return only foo
if foo = 0 and bar = 0 -> return false
You see:
00
10
01
11
00
If I insert another variable I'll get a lot of more opportunities and that is realy bad. Because I'll get realy big if statements.
Can somebody tells me another opportunitie to achive the same result?
Thank you.
I'd do it like this:
$sql_condition = '( 1=2 '; // one fake-condition, just to make it possible to start with 'OR' later
foreach($option[0] as $key => $value) { // iterate through all possible conditions
if($value===1) { // maybe exclude $keys that should not be used here
$sql_condition.=' OR post_type="'.$key.'"';
}
}
$sql_condition.=')';
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND '.$sql_condition.' ORDER BY post_title ASC', OBJECT );
Please try this code :
$sub_query = $operator = '';
if($option[0]->posts == 1)
{
$sub_query = 'post_type="page"';
$operator = ' OR';
}
if($option[0]->pages == 1)
{
$sub_query .= $operator.' post_type="post"';
}
if(empty($sub_query))
{
return false;
}
else
{
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND ('.$sub_query.') ORDER BY post_title ASC', OBJECT );
}
Create an array($arr) and set the key like "0,0" and value like "$sql";
and your code will be like this:
$tempKey = $option[0]->pages . "," . $option[0]->posts;
if(isset($arr[$tempKey]) {
$results = $wpdb->get_results($arr[$tempKey]);
}
So when you want to add more pages and posts all you will do is to change the arr.
$types = [];
if ($option[0]->posts)
$types[] = '"post"';
if ($option[0]->pages)
$types[] = '"page"';
if (!$types)
return null;
$results = $wpdb->get_results( 'SELECT * FROM '.$wpdb->prefix.'posts WHERE post_status="publish" AND (post_type IN ('. implode(',', $types) .')) ORDER BY post_title ASC', OBJECT );

How to deduce the count of the vacancies next to the name of the city?

I made a sql query that counts of jobs in a particular city
$countVac = Yii::app()->db->createCommand()
->select(array('cityId', 'count(*)'))
->from('mnk_vacancy')
->group('cityId')
->queryRow();
My function for deduce city
public function getCityList()
{
$cityList = $this->findAll(array('order' => 'name'));
$cityArray = CHtml::listData($cityList, 'id', 'name');
return $cityArray;
}
How do I make something like this
public function getCitiesWithVacanciesNumber()
{
//raw sql
$sql = '
SELECT
c.name city_name,
COUNT(v.id) vac_num
FROM cities c
LEFT JOIN mnk_vacancy v
ON v.cityId = c.id
GROUP BY c.name
';
return $this->getDbConnection()->createCommand($sql)->queryAll();
/*
AR:
'vacancies' => array(self::HAS_MANY, 'Vacancy', 'cityId', 'together' => true,)
*/
$rows = array();
$cities = self::model()->with('vacancies')->findAll();
foreach ($cities as $city) {
$rows[] = array(
'city_name' => $city->name,
'vac_num' => count($city->vacancies)
);
}
return $rows;
}

php sort after query fired

I want to sort highest to lowest cip and also lowest to highest cip, but cip value is not stored in database, it is calculated as soon as query is fired.
Here is html code to select sorting:
<select name="cip">
<option>Select CIP percentage</option>
<option value="1">Highest To Lowest</option>
<option value="2">Lowest To Highest</option>
</select>
And here is the query that I fired!
$select_applicant = "SELECT j.*, u.id, u.gender
FROM job_apply j
LEFT JOIN users u
ON u.id = j.user_id
WHERE j.job_id = '".$jid."'";
$result_applicant = mysqli_query($con, $select_applicant);
while($row_applicant = mysqli_fetch_assoc($result_applicant))
{
$user_id = $row_applicant["user_id"];
$user_info = get_user_profile_info($user_id);
$ratings_dist = get_skill_ratings_stats($user_id);
$got_it_total_rating = 0;
foreach($ratings_dist as $category=>$rating)
{
$got_it_total_rating = $got_it_total_rating + $rating['score'];
}
$got_it_total_category = count($ratings_dist);
$total_cip = ceil($got_it_total_rating / $got_it_total_category);
echo $total_cip;
}
Function "get_skill_ratings_stats" in php is as below:
function get_skill_ratings_stats($user_id){
global $con;
$items = array();
if($user_id>0)
{
$sql = "SELECT
s.category_id category_id,
c.name as category,
COALESCE(r.score_quality, 0.0) quality,
COALESCE(r.score_timing, 0.0) timing,
COALESCE(r.score_budget, 0.0) budget,
COALESCE(r.score_resp, 0.0) resp,
COALESCE(r.score_pro, 0.0) pro
FROM `user_skills` s
LEFT JOIN `skill_categories` c
ON c.category_id=s.category_id
LEFT JOIN `skill_ratings` r
ON r.skill_id=s.skill_id
WHERE s.user_id = '".(int)$user_id."'
AND s.status = 'active'
ORDER BY category ASC";
$prev_cat = '';
$result = mysqli_query($con, $sql);
// die(mysqli_error($con));
while($row = mysqli_fetch_assoc($result))
{
// print_r($row);
if(!$row['category']) continue;
if($row['category']!=$prev_cat)
{
if(isset($items[$prev_cat]['score']) && $items[$prev_cat]['score']>0 && count($items[$prev_cat])>1)
{
$items[$prev_cat]['score'] = floor(($items[$prev_cat]['score']*20)/(count($items[$prev_cat])-1));
}
$prev_cat = $row['category'];
}
if(!isset($items[$prev_cat]['score'])) $items[$prev_cat]['score'] = 0;
$items[$prev_cat][] = $row;
$items[$prev_cat]['score'] += ($row['quality']+$row['timing']+$row['budget']+$row['resp']+$row['pro'])/5;
}
}
// print_r($items);
// die();
if(isset($items[$prev_cat]['score']) && $items[$prev_cat]['score']>0 && count($items[$prev_cat])>1)
{
$items[$prev_cat]['score'] = floor(($items[$prev_cat]['score']*20)/(count($items[$prev_cat])-1));
}
$tmp = array();
foreach($items as $cat=>$item) {
$tmp[$item['score'].'-'.$cat] = $item;
}
krsort($tmp);
$items = array();
foreach($tmp as $k=>$v) {
$k = preg_replace('#^\d+-#is', '', $k);
$items[$k] = $v;
}
// print_r($tmp);
// print_r($items);
// die();
return $items;
}
Please help me! Having hard time with this!
Assuming that you are using a html table to display this I would just go with http://datatables.net/ , it will give you a lot of sorting options very easily...
Otherwise usort():
function cip($a, $b)
{
if ($a['cip'] == $b['cip']) {
return 0;
}
return ($a['cip'] < $b['cip']) ? -1 : 1;
}
$data = array(
[0] => array('cip' => 1)
[1] => array('cip' => 5)
[2] => array('cip' => 2)
);
usort($data, "cip");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
Assuming your array looks something like this:
array(
[0] => array('cip' => 1)
[1] => array('cip' => 5)
[2] => array('cip' => 2)
)
It basically loops til everything is sorted, all you do in the call back function is tell it which values to compare...
EDIT:
$total_cips[] = array('user_id' => $user_id, 'cip' => ceil($got_it_total_rating / $got_it_total_category));
Ok So now you have all the total cips in an array with there user_id right?
And outside for loop you call usort($total_cips, "cip");
Then you have a sorted array, if you wish to change the sorting direction just change the greater than to a less than in the cip function
as We0 said,
$total_cips[] = array('user_id' => $user_id, 'cip' => ceil($got_it_total_rating / $got_it_total_category));
but then i used multisort function:
function multi_sort($array, $akey)
{
function compare($a, $b)
{
global $key;
return strcmp($a[$key], $b[$key]);
}
usort($array, "compare");
return $array;
}
And then I call the function as below:
$total_cips = multi_sort($total_cips, $key = 'cip');
Finally this one worked!
Anyways thanks We0 & Ankit
Here:
$select_applicant = "SELECT j.*, u.id, u.gender
FROM job_apply j
LEFT JOIN users u
ON u.id = j.user_id
WHERE j.job_id = '".$jid."";
You are missing closing quote for $jid. It should be:
$select_applicant = "SELECT j.*, u.id, u.gender
FROM job_apply j
LEFT JOIN users u
ON u.id = j.user_id
WHERE j.job_id = '".$jid."'";
This might be one of the cause of your problem.

Categories