Is it possible to sorting based on data inside while loop? without using the sql order by.
But also after i select which column, it will sort desc or asc based on data inside not sort by database column and limit it only 10 every page
lookup.php
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = $_POST['search']['value']; // Search value
## Custom Field value
$searchByName = $_POST['searchByName'];
$searchByGender = $_POST['searchByGender'];
$sel = $con->query("SELECT * FROM a, b WHERE a.nrek=b.nrek GROUP BY a.name");
$records = $con->num_rows();
$totalRecords = $records;
## Total number of records with filtering
$sel = $con-query("SELECT * FROM a, b WHERE a.nrek=b.nrek AND 1 ".$searchQuery."GROUP BY a.name");
$records = $con->num_rwos();
$totalRecordwithFilter = $records;
$empQuery = $con->query("SELECT * FROM a, b, c WHERE a.nrek=b.nrek AND a.kode=c.kode AND a.kode='3' GROUP BY a.nrek ORDER BY ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage");
while ($row1 = $empquery->fetch_array())
{
$querybalance2 = $con->query("SELECT SUM(b.balance) as balance FROM a JOIN a ON a.nrek= b.nrek WHERE a.kode= '$row1[kode]' AND b.period='$_SESSION[lastperiod]'");
$querybalance2 = $con->query("SELECT SUM(b.balance) as balance FROM a JOIN a ON a.nrek= b.nrek WHERE a.kode= '$row1[kode]' AND b.period='$_SESSION[newperiod]'");
$balance2 = $querybalance2->fetch_array();
$balance1 = $querybalance1->fetch_array();
$data[] = array(
"arek"=>$row1[nrek],
"balance1"=>$balance1,
"balance2"=>$balance2
);
}
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
Ajax.js
var dataTable = $('#empTable').DataTable
({
'processing': true,
'serverSide': true,
'serverMethod': 'post',
//'searching': false, // Remove default Search Control
'ajax':
{
'url':'lookup.php',
'data': function(data)
{
}
},
'columns':
[
{ data: 'arek' },
{ data: 'balance1', className: 'text-center' },
{ data: 'balance2', className: 'text-center' },
]
});
html.php
<table id="empTable" class="display dataTable">
<thead>
<tr>
<th>Nrek</th>
<th>Balance1</th>
<th>Balance2</th>
</tr>
</thead>
</table>
I want to limit it so the data will load and display faster. If user click on the column, datatable will sort it based on data not column. I tried but "invalid json response", because there isn't "balance2" column in database.
Need help and thank you
Related
I want to get sum of column from two different tables in sequilize.
I want to accurate totalpaid, refunded & refundable field, which vary according to group by, I'm not be able to resolve it.
//Some pre-desined variables
var totalPaidQueryStr = '(CASE WHEN (SUM(inv_payment_record_invoices.payment)) IS NULL THEN 0 ELSE (SUM(inv_payment_record_invoices.payment)) END)';
var totalPaidQuery = [Sequelize.literal(totalPaidQueryStr), 'totalpaid']; //Get the total paid amount till date;
var refundedQueryStr = '(CASE WHEN (SUM(inv_payment_record_refunds.amount)) IS NULL THEN 0 ELSE (SUM(inv_payment_record_refunds.amount)) END)';
var refundedQuery = [Sequelize.literal(refundedQueryStr), 'refunded']; //Get the total paid amount till date
var refundableQueryStr = `(inv_payment_records.amount - (${totalPaidQueryStr} + ${refundedQueryStr}))`;
var refundableQuery = [Sequelize.literal(refundableQueryStr), 'refundable']; //Get the total due amount
return InvPaymentRecords.findOne({
attributes: [
'customer_id',
'amount',
'company_currency_id',
'exchange_rate',
totalPaidQuery, //Want to accurate sum
refundedQuery, //Want to accurate sum
refundableQuery
],
where: {
'id': payment_record_id,
'company_id': company_id
},
include: [
{
model: InvPaymentRecordInvoices,
require: false,
attributes: [],
},
{
model: InvPaymentRecordRefund,
require: false,
attributes: [],
}
],
group: [
//'inv_payment_records.id',
//'inv_payment_record_invoices.id',
//'inv_payment_record_refunds.id'
]
}).then(iprdata => {
return sequelize.Promise.resolve(iprdata);
}).catch(error => {
return sequelize.Promise.reject(error);
})
I have problem on laravel. I want to showing percentage on with eloquent, but return null value
This Is My Controller
$group_categories = Proyek::with(['modul' => function($query){
$query->select(DB::raw('((select count(*) from modul where status = 0 and deleted_at IS NULL) /
(select count(*) from modul where deleted_at IS NULL)) *
100 as count' ));
}])->get();
This Is Json return
{
id: "10",
proyek: "JuZka",
created_at: "2018-08-12 01:54:04",
updated_at: "2018-09-23 05:49:13",
modul: [ ]
},
You can use code like this:
$all_models = (new Proyek)->count();
$models = (new Proyek)->where('status', 0)->count();
$percentage = $models / $all_models * 100;
$group_categories = Proyek::wheere('modul', $percentage);
Hi guys I have a problem in my query in model, I'll show you the code before I explain it.
for($x = 1; $x <= count($this->input->post('subparticulars')); $x++) {
$feetype = $this->input->post('subparticulars')[$x];
$student = $this->input->post('substudentid');
$schoolyear = $this->input->post('subschoolyeardata');
$month = $this->input->post('month');
$payment = $this->input->post('subpaymentamount')[$x];
$this->db->set('statement_amount', '`statement_amount` -'. $payment, FALSE);
$this->db->where(array('feetype_id !=' => 2, 'feetype_id !=' => 3, 'feetype_id' => $feetype, 'student_id' => $student, 'schoolyear_id' => $schoolyear, 'month_id' => $month));
$status3 = $this->db->update('tbl_statement');
}
Here I have an add dynamic add row function which has contains the amounts and particulars of multiple payment in subparticulars and subpayments, I'm running a query that will minus my payments in my statement_amounts, as you can see in the $this->db->set. Now, I have a problem with my where clause, if you will try to understand my where clause this is the conditions.
I want to update all my fees except the one that has the feetype_id: 2 and 3, but the other feetype_id will be updated, How can I achieve this. When I'm running the code it still subtracts the fees that have feetype_id of 2 and 3.
Here's the correct answer
for($x = 1; $x <= count($this->input->post('subparticulars')); $x++) {
$feetype = $this->input->post('subparticulars')[$x];
$student = $this->input->post('substudentid');
$schoolyear = $this->input->post('subschoolyeardata');
$month = $this->input->post('month');
$payment = $this->input->post('subpaymentamount')[$x];
if ($feetype == 2 OR $feetype == 3)
{
$this->db->set('statement_amount', '`statement_amount` -'. $payment, FALSE);
$this->db->where(array('feetype_id' => $feetype, 'student_id' => $student, 'schoolyear_id' => $schoolyear));
$status3 = $this->db->update('tbl_statement');
}
else {
$this->db->set('statement_amount', '`statement_amount` -'. $payment, FALSE);
$this->db->where(array('feetype_id' => $feetype, 'student_id' => $student, 'schoolyear_id' => $schoolyear, 'month_id' => $month));
$status3 = $this->db->update('tbl_statement');
}
}
3 tables in MYSQL
table_product - product_id, product_name
table_variane - variant_id, variant_name
table_product_variants - product_id, variant_id, MRP, SellPrice
I want to create JSON data out of those in Perl for all the products, in this format:
[
{
"ProductID": "1",
"ProductName": "Green Detergent Bar",
"Variants": [
{
"VariantID": "1",
"VariantName": "500GM",
"MRP": "20.00",
"SellPrice": "19.50"
},
{
"VariantID": "2",
"VariantName": "1KG",
"MRP": "40.00",
"SellPrice": "38.00"
}
]
},
{
"ProductID": "2",
"ProductName": "ABCD",
"Variants": [
{
"VariantID": "3",
"VariantName": "1KG",
"MRP": "200.00",
"SellPrice": "190.50"
},
{
"VariantID": "2",
"VariantName": "1KG",
"MRP": "40.00",
"SellPrice": "38.00"
}
]
}
]
This is Perl Code
my $sql_query = ""; //need to fill this.
my $statement = $db_handle->prepare ($sql_query) or die "Couldn't prepare query '$sql_query': $DBI::errstr\n";
$statement->execute() or die "SQL Error: $DBI::errstr\n";
my #loop_data = ();
while (my #data = $statement->fetchrow_array())
{
my %data = //need to fill this too.
push(#loop_data, \%data);
}
my $json_text = to_json(\#loop_data);
print $json_text;
Please help in filling SQL query and while loop.
Its just a blueprint. Any modification in code is also fine.
That you need arrays (not hashes) complicates things a bit.
Option 1
Use two queries, one that finds the products, and one that finds the variants of a product.
my $product_sth = $dbh->prepare("
SELECT product_id,
product_name
FROM table_product
");
my $variant_sth = $dbh->prepare("
SELECT tv.variant_id,
tv.variant_name,
tvp.MRP,
tvp.SellPrice
FROM table_product_variants AS tpv
JOIN table_variant AS tv
ON tpv.variant_id = tv.variant_id
WHERE tpv.product_id = ?
");
my #data;
while (my $product_row = $product_sth->fetchrow_hashref()) {
my #variants;
$variant_sth->execute($product_row->{product_id});
while (my $variant_row = $variant_sth->fetchrow_hashref()) {
push #variants, {
VariantID => $variant_row->{variant_id},
VariantName => $variant_row->{variant_name},
MRP => $variant_row->{MRP},
SellPrice => $variant_row->{SellPrice},
};
}
push #data, {
ProductID => $product_row->{product_id},
ProductName => $product_row->{product_name},
Variants => \#variants,
};
}
my $data_json = to_json(\#data);
Option 2
Use an HoA to group the variants of a product when using a single query.
my $sth = $dbh->prepare("
SELECT tp.product_id,
tp.product_name,
tv.variant_id,
tv.variant_name,
tvp.MRP,
tvp.SellPrice
FROM table_product AS tp
JOIN table_product_variants AS tpv
ON tp.product_id = tpv.product_id
JOIN table_variant AS tv
ON tpv.variant_id = tv.variant_id
");
my %data;
while (my $row = $sth->fetchrow_hashref()) {
my $product_id = $row->{product_id};
my $product = $data{$product_id} ||= {
ProductID => $row->{product_id},
ProductName => $row->{product_name},
Variants => [],
};
push #{ $product->{Variants} }, {
VariantID => $row->{variant_id},
VariantName => $row->{variant_name},
MRP => $row->{MRP},
SellPrice => $row->{SellPrice},
};
}
my $data_json = to_json([ values(%data) ]);
Option 3
Use sorting to group the variants of a product when using a single query.
my $sth = $dbh->prepare("
SELECT tp.product_id,
tp.product_name,
tv.variant_id,
tv.variant_name,
tvp.MRP,
tvp.SellPrice
FROM table_product AS tp
JOIN table_product_variants AS tpv
ON tp.product_id = tpv.product_id
JOIN table_variant AS tv
ON tpv.variant_id = tv.variant_id
ORDER BY tp.product_id
");
my $last_product_id = 0;
my #data;
while (my $row = $sth->fetchrow_hashref()) {
my $product_id = $row->{product_id};
if ($product_id != $last_product_id) {
$last_product_id = $product_id;
push #data, {
ProductID => $row->{product_id},
ProductName => $row->{product_name},
Variants => [],
};
}
push #{ $data[-1]{Variants} }, {
VariantID => $row->{variant_id},
VariantName => $row->{variant_name},
MRP => $row->{MRP},
SellPrice => $row->{SellPrice},
};
}
my $data_json = to_json(\#data);
It's a little extra work than option 2, but it has the smallest client-side memory footprint (if you didn't have to keep everything in memory).
I have the following issue to solve.
I have an IQueryable list of Invoices, each tied to an Account. Each Account can have multiple Structures, and Accounts and Structures are tied together by a table called StructureAccount. It looks like this:
Invoice ---> Account <-----StructureAccount ----> Structure
I want to query my IQueryable list of Invoices and group by Structure.StructureID or StructureAccount.StructureID. But, because any given invoice can be tied to multiple Structures the best I can get is a LIST of StructureIDs, and therefore my GroupBy is not working.
I feel like I am missing an obvious solution to this.
I should note that I understand that the data in any one Invoice would be counted multiple times if the Invoice were tied to more than one Structure, and this is "solved" by a "PercentAllocationtoStructure" value in the table StructureAccount.
I hope I did a good enough job explaining this problem. Let me know if not.
Hmmm...I might be missing something, but doesn't the following work?
var q = from i in Invoice
join a in Account
on i.AccountID equals a.AccountID
join sa in StructureAccount
on i.AccountID equals sa.AccountID
join s in Structure
on sa.StructureID equals s.StructureID
group i by s.StructureID;
I tested it on the following dummy data:
var Invoice = new [] {
new { InvoiceID = 1, AccountID = 1 },
new { InvoiceID = 2, AccountID = 2 },
new { InvoiceID = 3, AccountID = 3 },
new { InvoiceID = 4, AccountID = 1 },
new { InvoiceID = 5, AccountID = 2 },
new { InvoiceID = 6, AccountID = 3 }
};
var Account = new [] {
new { AccountID = 1 },
new { AccountID = 2 },
new { AccountID = 3 },
};
var StructureAccount = new [] {
new { AccountID = 1, StructureID = 2 },
new { AccountID = 1, StructureID = 3 },
new { AccountID = 2, StructureID = 2 },
new { AccountID = 3, StructureID = 1 },
new { AccountID = 3, StructureID = 2 },
};
var Structure = new [] {
new { StructureID = 1 },
new { StructureID = 2 },
new { StructureID = 3 }
};
And it returns:
StructureID = 2:
InvoiceID's: 1,2,3,4,5,6
StructureID = 3:
InvoiceID's: 1,4
StructureID = 1:
InvoiceID's: 3,6
I'll assume you have the following starting point:
IQueryable<Invoice> _invoices;
First, you need to get a list of all the items that you will be iterating over:
IQueryable<Account> _accounts = _invoices.Select(myInvoice => myInvoice.Account).Distinct();
IQueryable<StructuredAccount> _structuredAccounts = _accounts.SelectMany(myAccount => myAccount.StructuredAccounts);
IQueryable<Structure> _structures = _structuredAccounts.Select(myStructuredAccount => myStructuredAccount.Structure).Distinct();
Next, you need to go back and join your Structure objects to the respective Invoice objects.
For this, you'll:
Get a set of {Structure, Account} pairs:
var structureAccountJoin = _structures.Join(_structuredAccounts, _structure => structure.StructuredID, _structuredAccount => _structuredAccount.StructuredID, (structure, structuredAccount) => new { Structure = structure, Account = structuredAccount.Account });
Get a set of {Structure, Invoice} pairs:
var structureInvoiceJoin = structureAccountJoin.Join(_invoices, myObj => myObj.Account.AccountID, invoice => invoice.AccountID, (myObj, invoice) => new { Structure = myObj.Structure, Invoice = invoice});
Finally, you can group everything by the Structure object:
IQueryable<IGrouping<Structure, Invoice>> groupByStructure = structureInvoiceJoin.GroupBy(obj => obj.Structure, result => result.Invoice);
(GroupBy documentation: http://msdn.microsoft.com/en-us/library/bb534304.aspx)
Now, you can access everything as follows:
foreach(IGrouping<Structure, Invoice> groupEntry in groupByStructure)
{
Structure currentGrouping = groupEntry.Key;
foreach(Invoice inv in groupEntry)
{
// do something;
}
}
As a note, this is a very complex script that requires a lot of steps if you don't have access to the tables directly. You may want to look into creating a StoredProcedure for this instead, as it will be more efficient and you'll be able to use SQL Joins instead. If you have only an IQueryable<Invoice> to work with and access to nothing else, there is probably a design problem somewhere in your architecture.
Nevertheless, this is the way to make it work based on your requirements, if I read them correctly.