Getting column value when SQL query has aliases - php

I have a SQL query that has alias in it. The problem is, when I try to get the values of columns it doesn't show the correct values:
$sql = "SELECT p.ID, p.ProfileID, p.ModuleID, p.View, p.Add, p.Edit, p.Delete, m.Name, m.ID FROM permission AS p, module AS m WHERE p.ModuleID = m.ID ORDER BY p.ProfileID ASC, m.Name ASC";
$result = array();
$i = 0;
foreach ($this->dbconnect->query($sql) as $row)
{
$result[$i] = array(
'ID' => $row['p.ID'],
'ProfileID' => $row['p.ProfileID'],
'ModuleID' => $row['p.ModuleID'],
'View' => $row['p.View'],
'Add' => $row['p.Add'],
'Edit' => $row['p.Edit'],
'Delete' => $row['p.Delete']);
$i += 1;
}
Running shows no value when in the database it's actually 10.
If I change the above code to the following:
$sql = "SELECT p.ID, p.ProfileID, p.ModuleID, p.View, p.Add, p.Edit, p.Delete, m.Name, m.ID FROM permission AS p, module AS m WHERE p.ModuleID = m.ID ORDER BY p.ProfileID ASC, m.Name ASC";
$result = array();
$i = 0;
foreach ($this->dbconnect->query($sql) as $row)
{
$result[$i] = array(
'ID' => $row['ID'],
'ProfileID' => $row['ProfileID'],
'ModuleID' => $row['ModuleID'],
'View' => $row['View'],
'Add' => $row['Add'],
'Edit' => $row['Edit'],
'Delete' => $row['Delete']);
$i += 1;
}
Miraculously, running shows the value of m.ID instead of p.ID. It is strange why the first example is incorrect. Am I missing something here?

You should something like this...
SELECT p.ID as p_ID, ...
And
'ID' => $row['p_ID'],

Use aliases in SELECT to each column, which are same:
$sql = "SELECT p.ID AS permission_id, p.ProfileID, p.ModuleID, p.View, p.Add, p.Edit, p.Delete, m.Name, m.ID AS module_id FROM permission AS p, module AS m WHERE p.ModuleID = m.ID ORDER BY p.ProfileID ASC, m.Name ASC";
then:
foreach(...)
{
$result[$i] = array(
'Perm_ID' => $row['permission_id'],
'Module_ID' => $row['module_id'],
...
}

Related

MySQL : one query for join multiple tables and store result in 3arrays

I'm trying to write one query for joining 3 tables without link, I was trying with UNION SQL command like this:
SELECT *
FROM
(SELECT
a.id AS field_aa, a.column2 AS field_ab, a.column3 AS field_ac
FROM tableA a
UNION
SELECT
b.id AS field_ba, b.column2 AS field_bb, b.column3 AS field_bc
FROM tableB b
UNION
SELECT
c.id AS field_ca, c.column2 AS field_cb, c.column3 AS field_cc
FROM tableC c) abc
WHERE 1;
And after i want to fill 3 arrays for each table
while( ($arr = $_opDB->fetch_assoc($result)) != FALSE ) {
$array_one = array(
'field_id' => $arr['field_aa'],
'field_one' => $arr['field_ab'],
'field_two' => $arr['field_ac'],
) ;
$array_two = array(
'field_id' => $arr['field_ba'],
'field_one' => $arr['field_bb'],
'field_two' => $arr['field_bc'],
) ;
$row_three = array(
...
) ;
$global_array['firstSelect'][] = $array_one ;
$global_array['secondSelect'][] = $array_two ;
$global_array['thirdSelect'][] = $array_three ;
}
All my entries are added in $global_array['firstSelect'], others are empty
You could add a field indicating from which table a row is coming:
SELECT a.id AS field_id,
a.column2 AS field_2,
a.column3 AS field_3,
'firstSelect' as select_name
FROM tableA a
UNION
SELECT b.id AS field_id,
b.column2 AS field_2,
b.column3 AS field_3,
'secondSelect' as select_name
FROM tableB b
UNION
SELECT c.id AS field_id,
c.column2 AS field_2,
c.column3 AS field_3,
'thirdSelect' as select_name
FROM tableC c
And here is the PHP to process the result:
while(($row = $_opDB->fetch_assoc($result)) {
$select = $row['select_name'];
$global_array[$select][] = ['field_id' => $row['field_id'],
'field_one' => $row['field_2'],
'field_two' => $row['field_3']];
}
As CBroe rightly commented: If the tables are indeed identical you should make them into one table.

How do I Compare outer variable from a nested loop in php

I'm fetching data from two table Tenders and payments I want to display monthly payments with monthly tenders in on array.
But I need to compare if the month and year from the first loop is the same as the month and year from the nested loop
$first_sql = "SELECT YEAR(toll.transaction_date) 'year', MONTHNAME(toll.transaction_date) 'month', COUNT(toll.toll_id) 'count', SUM(toll.tender) 'tender'
FROM toll WHERE company_id = '$COMPANY_ID'
GROUP BY YEAR(toll.transaction_date), MONTHNAME(toll.transaction_date), MONTH(toll.transaction_date)
ORDER BY YEAR(toll.transaction_date) DESC, MONTH(toll.transaction_date) DESC limit 5;";
$scnd_sql = "SELECT YEAR(company_payment_detail.payment_date) 'year', MONTHNAME(company_payment_detail.payment_date) 'month', SUM(company_payment_detail.payment_amount) 'payment'
FROM company_payment_detail
JOIN company_account ON company_payment_detail.company_account_id = company_account.company_account_id
JOIN company ON company.company_id = company_account.company_id
WHERE company_account.company_id = '$COMPANY_ID'
GROUP BY YEAR(company_payment_detail.payment_date), MONTHNAME(company_payment_detail.payment_date),MONTH(company_payment_detail.payment_date)
ORDER BY YEAR(company_payment_detail.payment_date) DESC, MONTH(company_payment_detail.payment_date) DESC limit 5";
The Results
The Loops
$run_first_sql= $conn->query($first_sql);
$run_scnd_sql = $conn->query($scnd_sql);
$chart_data = [];
//first loop
while($row= $run_first_sql->fetch_assoc()){
$arr1 = array(
'y' => $row['year'],
'm' => $row['month'],
'c' => (int)$row['count'],
't' => (float)$row['tender']
);
while($row2= $run_scnd_sql->fetch_assoc()){
if($row['year'] == $row2['year'] && $row['month'] == $row2['month']){
$arr2 = array(
'p' =>(float)$row2['payment'],
);
}else{
$arr2 = array(
'p' =>(float)0,
);
}
}
$arr1 = array_merge($arr1, $arr2);
array_push($chart_data1, $arr1);
}
print_r($chart_data1);
Do a LEFT JOIN of the two queries. If there's no row in the second query for the same month, you'll get NULL in those columns.
SELECT t1.year, t1.month, t1.count, t1.tender, IFNULL(t2.payment, 0) AS payment
FROM (
SELECT YEAR(toll.transaction_date) 'year', MONTHNAME(toll.transaction_date) 'month', COUNT(toll.toll_id) 'count', SUM(toll.tender) 'tender'
FROM toll WHERE company_id = '$COMPANY_ID'
GROUP BY year, month
ORDER BY year DESC, month DESC
limit 5) AS t1
LEFT JOIN (
SELECT YEAR(company_payment_detail.payment_date) 'year', MONTHNAME(company_payment_detail.payment_date) 'month', SUM(company_payment_detail.payment_amount) 'payment'
FROM company_payment_detail
JOIN company_account ON company_payment_detail.company_account_id = company_account.company_account_id
JOIN company ON company.company_id = company_account.company_id
WHERE company_account.company_id = '$COMPANY_ID'
GROUP BY year, month
ORDER BY year DESC, month DESC
limit 5) AS t2
ON t1.year = t2.year AND t1.month = t2.month
You can perform that in a single query, the year and month of both table can be used as their relationship. The query will be looked like this:
$sql = 'SELECT * FROM tenders, payments WHERE tenders.year=payments.year AND tenders.month=payments.month';
while($row = $sql ->fetch_assoc()){
$data = array(
'month' => $row2['month'],
'year' => $row2['year'],
'count' => $row2['count'],
'tender' => $row2['tender'],
);
}
All the tenders year that is equal to payments year AND tenders month that is equal payments month will be fetched.
So if you are going to stick with your way of fetching data, your if condtion code will look like this:
while($row = $run_first_sql->fetch_assoc()){
while($row2 = $scnd_sql ->fetch_assoc()){
if($row['month'] == $row2['month'] && $row['year'] == $row2['year']){
$data = array(
'month' => $row['month'],
'year' => $row['year'],
'count' => $row['count'],
'tender' => $row['tender'],
);
}
}
}
The data of the first query as it iterate will be checked in your second query which takes time.

How to access a particular value from mysql database using php?

This is my php script that selects everything from invoiceNo where invoiceNo is distinct.
<?php
require 'init.php';
$query = 'SELECT * FROM `selected_items` WHERE invoiceNo IN ( SELECT DISTINCT ( invoiceNo) AS invoiceNo FROM selected_items ) GROUP BY invoiceNo;';
$res = mysqli_query($con, $query);
$result = [];
while ($row = mysqli_fetch_array($res)) {
array_push($result, [
'custInfo' => $row[0],
'invoiceNo' => $row[1],
'barcode' => $row[2],
'description' => $row[3],
'weight' => $row[4],
'rate' => $row[5],
'makingAmt' => $row[6],
'net_rate' => $row[7],
'itemTotal' => $row[8],
'vat' => $row[9],
'sum_total' => $row[10],
'bill_type' => $row[11],
'date' => $row[12],
'advance' => $row[13],
'balance' => $row[14],
]);
}
echo json_encode(['result' => $result]);
mysqli_close($con);
Right now this script gives me the first value from sum_total i.e it gives me the first row from my database how can I get the last row.I am new to programming any suggestions or help is appreciated.Thanks :)
Select * From (
SELECT t.*,
#rownum := #rownum + 1 AS rank
FROM selected_items t,
(SELECT #rownum := 0) r order by rank DESC
) si GROUP BY si.invoiceNo;
This query solved my problem
Try this, i think this is you want, may it help
$query ="SELECT max( `sum_total` ) FROM `selected_items` GROUP BY invoiceNo;";
try like this :
$query ="SELECT * FROM `selected_items` WHERE invoiceNo IN ( SELECT DISTINCT ( invoiceNo) AS invoiceNo FROM selected_items ) ORDER BY `sum_total` DESC";
$query ="SELECT max( `sum_total` ) FROM selected_items";
Where column_name can be vary.
If you need to get only last record use limit.
$query ="SELECT * FROM `selected_items` GROUP BY invoiceNo ORDER BY `sum_total` DESC limit 1;
If you need to get highest to lowest sum_total record try the below code,
$query ="SELECT * FROM `selected_items` where `sum_total` = (SELECT max( `sum_total` ) FROM `selected_items` GROUP BY invoiceNo) GROUP BY invoiceNo ORDER BY `sum_total` DESC;

Laravel Query Builder "select" strange behaviour

I have a problem with the following code:
public function index() {
$qObj = \DB::table('customers as c')
->join('companies_has_customers as chc', 'chc.comhc_cus_id', '=', 'c.cus_id')
->join('cuscategory as cc', 'chc.comhc_cca_id', '=', 'cc.cca_id')
->join('transactions as t','t.trn_cus_id', '=','c.cus_id')
->select('t.trn_id');
$qObj->where('comhc_com_id', '=', $this->companyId);
$res = array(
'count' => $qObj->count(),
'items' => $qObj->get()
);
//print_r($this->showLastQuery());
return parent::prepareResponse($res, 200, 'customers');
}
And this piece of code produces following SQL query:
select * from `customers` as `c`
inner join `companies_has_customers` as `chc` on `chc`.`comhc_cus_id` = `c`.`cus_id`
inner join `cuscategory` as `cc` on `chc`.`comhc_cca_id` = `cc`.`cca_id`
inner join `transactions` as `t` on `t`.`trn_cus_id` = `c`.`cus_id`
where comhc_com_id` = 1
QUESTION:
Why QueryBuilder produce select *... instead of select t.trn_id... as is requested in above syntax?
Change the order:
$res = array(
'items' => $qObj->get(),
'count' => $qObj->count()
);
and it will work.
But better, instead of querying DB twice, do this:
$items = $qObj->get();
$res = array(
'items' => $items,
'count' => count($items)
);
The problem with your code is count() method behaviour - it resets the columns property (set with select), that's all.
Put it in $qObj->get(['t.trn_id']) like this:
$res = array(
'items' => $items = $qObj->get(['t.trn_id']),
'count' => count($items) // count the cached $items
);
Instead of select ( Remove select('t.trn_id')).

Select 3 tables in zend

I'm a new in Zend.
In my model Default_Model_ApplicationMapper, I wanna use a db-table Application_Model_DbTable_Application to run a query like that
"Select * from application as a, category as c, user as u where a.user_id = u.id and a.category_id = c.id";
I tried this:
$table = new Application_Model_DbTable_Application();
$select = $table->select()->from(array('a' => 'application'))
->from(array('c' => 'category'))
->from(array('u' => 'user'))
->where('a.user_id = u.id and a.category_id = c.id');
Of course this thing does not work.
Can you help me with this?
Instead of using from(array('a' => 'table')) three times, try using from(array('a' => 'table1', 'b' => 'table2', 'c' => 'table3')).

Categories