Sorting amount without using query? Datatables Codeigniter - javascript

I have problem sorting amounts because i have other query that has computation. The sorting is based in the main query but I need to sort it with the total amount(with computation)
I tried to use sorting in datatables but its not working because sorting in datables is based on the main query.
$sql = "SELECT mm.idno as idno,
TRIM(UPPER(CONCAT(mm.fname, ' ',mm.mname, ' ', mm.lname))) as fullname,
TRIM(UPPER(mm.branchname)) as branchname,
TRIM(UPPER(mm.address)) as outlet_address,
SUM(dr.totalamt) as total_amount
FROM 8_membermain mm
LEFT JOIN 8_directsalessummary dr
ON mm.idno = dr.idno
WHERE mm.status > 0
AND dr.status = 1
AND dr.ispaid = 'Full Payment'
AND dr.trandate BETWEEN '".$date1."' AND '".$date2."'
GROUP BY mm.idno ORDER BY total_amount DESC";
$query = $this->db->query($sql, $data);
foreach( $query->result_array() as $row ){ // preparing an array for table tbody
$nestedData = array();
$nestedData[] = $row["idno"];
$nestedData[] = $row["fullname"];
$nestedData[] = $row["branchname"];
$nestedData[] = $row["outlet_address"];
if(empty($minus_item_amount[$row["idno"]])){
$minus_item = 0;
}
else{
$minus_item = $minus_item_amount[$row["idno"]];
}
if(empty($return_amount[$row["idno"]])){
$return = 0;
}
else{
$return = $return_amount[$row["idno"]];
}
if(!empty($checkDRchecker[$row["idno"]])) {
$minus_item = 0;
} else{
}
$total_amount = ($row["total_amount"] - $minus_item) - $return;
$nestedData[] = number_format($total_amount,2,".",","); //total amount
$data[] = $nestedData;
}
As you see, the sorting of $row["total_amount"] is based in the main query. is there any possible way to sort the total amount?

Related

Multiple fields with the same name in AJAX and PHP

Everyone.
I got some good help a couple of days ago, so I'm hoping that someone can show me where I'm going wrong here. Basically, what I'm trying to do is update a MySQL database in the background when a user clicks a button. The form is a series of records, and the records have common field names (ID, DSA_Number, Manager_Review, etc.) Right now, the code doesn't even seem to return success or failure messages.
Here's the script on the main page:
<script>
$(document).ready(function(){
$("#button").click(function(){
var DDD_Number=$("#DDD_Number").val();
var Manager_Review=$("#Manager_Review").val();
var RID=$("#RID").val();
var Services=$("Services").val();
var Dues_List=$("Dues_List").val();
var ID=$("ID").val();
var myrid=$("myrid").val();
var Manager_Comments=$("Manager_Comments").val();
var President_Comments=$("President_Comments").val();
var dataTosend='?DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review+'&RID='+RID+'&Services='+Services+'&Dues_List='+Dues_List+'&Manager_Comments='+Manager_Comments+'&President_Comments='+President_Comments;
$.ajax({
type: "GET",
url:'baseupdater-test.php' + dataTosend,
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
},
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
}
});
});
</script>
Here's the code that draws the rows on the table:
<?php
/* This code writes the rows in the table for baserecord.php */
$n = 0;
$o = $n + 1;
$firstday = date('m/1/Y');
if(isset($_GET['MR'])) // If $_GET['MR'] is set ...
{
$MR = $_GET['MR']; // Set the variables.
$PR = $Pres_Rev;
}
else // If not, select the maximum (latest) Manager Review Date.
{
$getmr = "select max(STR_TO_DATE(Manager_Review_Date, '%m/%d/%Y')) as Manager_Review_Date,
President_Review_Date from clientdb.MRS2_test
inner join clients_MRS
on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
where SCID = '$ID';";
$rs2 = mysqli_query($con,$getmr);
$rvd = mysqli_fetch_assoc($rs2);
$MR = date('m/d/Y', strtotime($rvd['Manager_Review_Date']));
echo "MR: $MR<br>";
$PR = date('m/d/Y', strtotime($rvd['President_Review_Date']));
}
// The following query select the data for the row and orders it by the latest Manager Review Date.
$cliselect = "select distinct clientdb.Plans.Client_ID, clientdb.clients_MRS.DSA_Status, clientdb.clients_MRS.DSA_Status_Date, clientdb.clients_MRS.First_Name, clients_MRS.Last_Name, clientdb.clients_MRS.County, clientdb.Plans.DDD_Case, RID, Plans.Program, max(Plans.Plan) as MPlan, Tier, Plan_End_Date, clientdb.MRS2_test.RID, clientdb.MRS2_test.President_Comments, clientdb.MRS2_test.Manager_Comments, clientdb.MRS2_test.Services_Issues, clientdb.MRS2_test.Dues_List
from clientdb.Plans
inner join clientdb.clients_MRS on clientdb.clients_MRS.DDD_Case = clientdb.Plans.DDD_Case
inner join clientdb.MRS2_test on clientdb.MRS2_test.DDD_Number = clientdb.Plans.DDD_Case
where SCID = '$ID' and (DSA_Status = 'Active' OR (DSA_Status <> 'Active' AND STR_TO_DATE(DSA_Status_Date, '%d/%m/%Y') > STR_TO_DATE($firstday, '%m/%d/%Y'))) AND (Manager_Review_Date = '$MR')
group by clientdb.Plans.DDD_Case order by STR_TO_DATE(clientdb.MRS2_test.Manager_Review_Date, '%m/%d/%Y') DESC, clientdb.Plans.Last_Name;";
//echo "cliselect $cliselect<br>";
$cres = mysqli_query($con, $cliselect);
while ($dddr = mysqli_fetch_assoc($cres)) {
$DDD_Case = $dddr['DDD_Case'];
$First_Name = $dddr['First_Name'];
$Last_Name = $dddr['Last_Name'];
$County = $dddr['County'];
$Tier = $dddr['Tier'];
if($ddr['Plan_End_Date'] <> '')
{
$Plan_End_Date = $dddr['Plan_End_Date'];
}
$Pres_Comments = $dddr['President_Comments'];
$Mgr_Comments = $dddr['Manager_Comments'];
$Dues = $dddr['Dues_List'];
$Services = $dddr['Services_Issues'];
$RID = $dddr['RID'];
$mxselect = "select max(Plan) as MPlan from clientdb.Plans where clientdb.Plans.DDD_Case = '$DDD_Case';";
$rens = mysqli_query($con, $mxselect);
$rmm = mysqli_fetch_assoc($rens);
$MPlan = $rmm['MPlan'];
$endsel = "select Plan_End_Date, Program from clientdb.Plans where clientdb.Plans.DDD_Case = $DDD_Case and clientdb.Plans.Plan = $MPlan;";
$rsel = mysqli_query($con, $endsel);
$end = mysqli_fetch_assoc($rsel);
$Plan_End_Date = $end['Plan_End_Date'];
$Program = $end['Program'];
//The purpose of ths quer s to get the RID for each row.
$mrselect = "select * from MRS2_test where DDD_Number = '$DDD_Case' and Manager_Review_Date = '$MR'
group by DDD_Number, RID
order by RID DESC
Limit 1 ;";
$run = mysqli_query($con,$mrselect);
$mrss = mysqli_fetch_assoc($run);
$Manager_Review_Date = $mrss['Manager_Review_Date'];
$President_Review_Date = $mrss['President_Review_Date'];
$myRID = $mrss['RID'][$n];
echo "<tr><td>$o</td><td sorttable_customkey='$DDD_Case'><input class='ddd' type = 'text' value = '$DDD_Case' name = 'DDD_Number[]' size='6'></td><td sorttable_customkey='$Last_Name'>$First_Name $Last_Name</td><td>$County</td><td>$Program</td><td>$Tier</td><td sorttable_customkey='";
?>
<?php echo strtotime($Plan_End_Date);
echo "'>$Plan_End_Date</td><td><textarea class='expnd' name='Services[]'>$Services</textarea></td><td><input name='Dues_List[]'' type = 'text' value = '$Dues'></td><td><textarea class='expnd' name='Manager_Comments[]'>$Mgr_Comments</textarea></td><td><textarea class='expnd' name='President_Comments[]'>$Pres_Comments</textarea></td><td><input type='text' size='4' name = 'myrid[]' value='$RID' readonly></td><input type='hidden' name = 'manreview-orig' value='$Manager_Review_Date'></tr>";
$n = $n++;
$o++;
}
?>
And finally, this is the code that does the update:
<?php
include 'config.php';
$con = mysqli_connect($DB_server, $DB_user, $DB_password, $DB_database);
$Manager_Review = $_GET['Manager_Review'];
$Old_MR = $_GET['manreview-orig'];
//echo "OLD MR: $Old_MR<br>";
if($_GET['President_Review'] == '12/31/1969')
{
$President_Review = '';
}
if($_GET['President_Review'] <> '')
{
$President_Review = $_GET['President_Review'];
}
else
{
$President_Review = '';
}
$ID = $_GET['ID'];
$Services = $_GET['Services'];
echo "New Content!<br>";
$n = 0;
while ($n <= sizeof($_GET)) {
$ridselect = "select clientdb.MRS2_test.RID, clientdb.clients_MRS.DDD_Case, clientdb.clients_MRS.SCID from clientdb.MRS2_test
inner join clientdb.clients_MRS
on clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
where Manager_Review_Date = '$Old_MR' and clientdb.clients_MRS.DDD_Case = clientdb.MRS2_test.DDD_Number
order by RID;";
$rsc = mysqli_query($con, $ridselect);
$rowrid = mysqli_fetch_assoc($rsc);
$RID = $_GET['myrid'][$n];
// echo "RID: $RID<br>";
$MDD = $_GET['RID'];
$myrid = $_GET['myrid'][$n];
$DDD_Case = $_GET['DDD_Number'][$n];
$Period = ltrim(substr($Manager_Review,0,2), "0");
$Services = mysqli_real_escape_string($con, $_GET['Services'][$n]);
$Manager_Comments = mysqli_real_escape_string($con, $_GET['Manager_Comments'][$n]);
$President_Comments = mysqli_real_escape_string($con, $_GET['President_Comments'][$n]);
$Dues_List = mysqli_real_escape_string($con, $_GET['Dues_List'][$n]);
$DDD_Case = $_GET['DDD_Number'][$n];
$updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Services_Issues = '$Services',
clientdb.MRS2_test.Manager_Comments = '$Manager_Comments', clientdb.MRS2_test.President_Comments = '$President_Comments',
clientdb.MRS2_test.Dues_List = '$Dues_List', Period = '$Period' where DDD_Number = '$DDD_Case' and RID = '$RID';";
echo $updater . "<br>";
$date_updater = "update clientdb.MRS2_test set clientdb.MRS2_test.Manager_Review_Date = '$Manager_Review',
clientdb.MRS2_test.President_Review_Date = '$President_Review' where RID = '$RID';";
echo "dateupdater: $date_updater<br>";
if(!mysqli_query($con, $date_updater))
{
echo "That failed miserably.<br>";
}
else
{
$rws = mysqli_affected_rows($con);
echo "affected rows: $rws<br>";
echo "Success.<br>";
}
mysqli_query($con, $updater);
$datestamp = date('Y-m-d h:i:s');
$upstamp = "update clientdb.MRS2_test set Update_Time = '$datestamp' where DDD_Case = '$DDD_Case' and RID = '$RID';";
mysqli_query($con,$upstamp);
$n++;
}
echo "<script language='Javascript'>document.getElementById('stuffhere').InnerHTML = '<?php echo $updater; ?>';</script>";
?>
I've tried serializing the form, and I haven't had any success there. Any suggestions would be greatly welcome. Sorry for the long post, but I'm just not sure where the error is at this point.
Your code
var data= [DDD_Number,Manager_Review,RID,Services,Dues_List,ID,myrid,Manager_Comments,President_Comments];
var datatosend = JSON.stringify(data);
$.ajax({
type: "GET",
url:'baseupdater-test.php',
data:dataTosend,
async: true,
success:function(data){
document.getElementById('stuffhere').innerHTML.text = "Success.";
document.getElementById('stuffhere').innerHTML.text = data;
},
error: function(data){
document.getElementById('stuffhere').innerHTML.text = "Failure.";
}
});
As i can see you are trying to send the data twice, first through url and second with the ajax data method please fix that i think its a wrong approach to do that you should send it only once.
And moreover you must convert the data into json format to make the ajax request work
and now what's happening is as your data is not in the correct format your code must be stuck at the data in ajax you can see it in console the ajax request would not show you any value passing to another and that is the main reason the Success or Failure are not being show.

Condensing multiple sqlsrv_queries into a function

I have this couple queries, I am looking to making it run faster by creating a function like this. What would be the best way to do this? The queries find the tickets in the database that have been maintained
public function __select(){}
Below are the queries:
$data = array();
if($My_Privileges['User_Privilege'] >= 4 && $My_Privileges['Group_Privilege'] >= 4 && $My_Privileges['Other_Privilege'] >= 4){
$Tickets = array();
$r = sqlsrv_query($NEI,"
SELECT Elev.ID AS ID
FROM nei.dbo.Elev
LEFT JOIN nei.dbo.Loc ON Elev.Loc = Loc.Loc
WHERE Elev.Status = 0
AND Loc.Maint = 1
GROUP BY Elev.ID
;");
$data2 = array();
if($r){while($array = sqlsrv_fetch_array($r)){$data2[$array['ID']] = $array;}}
$sql = array();
foreach($data2 as $key=>$variable){$sql[] = "Elev.ID = '{$variable['ID']}'";}
$sql = implode(" OR ",$sql);
$r = sqlsrv_query($NEI,"
SELECT Max(TicketD.EDate) AS Last_Date,
Elev.ID AS ID
FROM nei.dbo.TicketD
LEFT JOIN nei.dbo.Elev ON TicketD.Elev = Elev.ID
LEFT JOIN nei.dbo.Job ON TicketD.Job = Job.ID
WHERE Job.Type = 0
AND ({$sql})
GROUP BY Elev.ID
;");
if($r){
while($array = sqlsrv_fetch_array($r,SQLSRV_FETCH_ASSOC)){
if(isset($data2[$array['ID']])){
$data2[$array['ID']]['Last_Date'] = $array['Last_Date'];
}
}
}
$r = sqlsrv_query($NEI,"
SELECT Elev.ID AS ID,
Elev.State AS State,
Elev.Unit AS Unit,
Elev.Type AS Type,
Loc.Tag AS Location,
Zone.Name AS Zone,
Emp.fFirst + ' ' + Emp.Last AS Route
FROM nei.dbo.Elev
LEFT JOIN nei.dbo.Loc ON Elev.Loc = Loc.Loc
LEFT JOIN nei.dbo.Zone ON Loc.Zone = Zone.ID
LEFT JOIN nei.dbo.Route ON Loc.Route = Route.ID
LEFT JOIN nei.dbo.Emp ON Route.Mech = Emp.fWork
WHERE Loc.Maint = 1
AND ({$sql})
;");
if($r){
while($array = sqlsrv_fetch_array($r,SQLSRV_FETCH_ASSOC)){
$array['Last_Date'] = substr($data2[$array['ID']]['Last_Date'],0,10);
$data[] = $array;
}
}
}
In another PHP file, I am creating a function called __select() and I have been trying to figure out the best way to condense the queries and make the website run faster. Any help would be appreciated.

refresh multiple classes every n secs from php backend

I have some code in jquery that connects to php and refreshes the class with latest data. This is working ok. However, I need to update 3 classes and when it refreshses the values are empty.
Is there a way I can query db and update 3 classes with fresh data every n sec. Many thanks
js
// Update server with latest actions,destructions and return requests
setInterval(function() {
$.get('/domain/admin/refreshBox.php', function(data) {
$(".actions").text(data);
$(".retrievals").text(data);
$(".returns").text(data);
});
}, 10000);
php
$sql= mysqli_query($conn,"SELECT count(*) as total FROM act WHERE new = '1'");
$rows = mysqli_fetch_assoc($sql);
$num = $rows['total'];
//echo $num;
$ni = $num;
if($ni < 1) {
$ni = '0';
}
echo $ni;
$nisql= mysqli_query($conn,"SELECT count(*) as ni FROM act WHERE activity='New Intake' AND new = '1'");
$niintknum_row = mysqli_fetch_assoc($nisql);
$niintknum = $niintknum_row['ni'];
//echo $num;
$niintk_num = $niintknum;
if($niintk_num < 1) {
$niintk_num = '0';
echo $niintk_num;
$brtvsql= mysqli_query($conn,"SELECT count(*) as rtrv FROM act WHERE activity='Box Retrieval' AND new = '1'");
$brtv_row = mysqli_fetch_assoc($brtvsql);
$brtvnum = $brtv_row['rtrv'];
//echo $num;
$brtv_num = $brtvnum;
if($brtv_num < 1) {
$brtv_num = '0';
echo $brtv_num;
$brtnsql= mysqli_query($conn,"SELECT count(*) as brtn FROM act WHERE activity='Box Return' AND new = '1'");
$brtn_row = mysqli_fetch_assoc($brtnsql);
$brtnnum = $brtn_row['brtn'];
//echo $num;
$brtn_num = $brtnnum;
if($brtn_num < 1) {
$brtn_num = '0';
}
echo $brtn_num;

Whats the fastest way to translate sqlite data to Google Chart format?

I have a sqlite database with the following scheme
CREATE TABLE `sensor` (
`id` TEXT NOT NULL UNIQUE,
`description` TEXT
);
CREATE TABLE `temperature` (
`time` INTEGER NOT NULL,
`sensor` TEXT NOT NULL,
`value` REAL,
FOREIGN KEY(`sensor`) REFERENCES sensor(id)
);
with temperature values from different sensors in it. One Entry looks like
unixtimestamp|sensor-id|temperature
1459802024|sensor1|22.0
I want to plot the data with the google Chart library (line plot). The javascript ajax-calls the following php-script:
<?php
ini_set("display_errors", 1);
//header('Content-Type: application/json');
$db = new SQLite3('/file/to/sqlite/db');
$result = $db->query('SELECT * FROM sensor');
$sensors = array();
$dataTable = array();
$interval = filter_input(INPUT_GET,'interval',FILTER_VALIDATE_INT, array("options"=>array("default" => time(),"min_range"=>0)));
$starttime = time() - $interval;
while($row = $result->fetchArray(SQLITE3_ASSOC)){
$sensors[$row['id']] = $row['description'];
}
$et = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
echo "</br>get available sensors: $et </br>";
$dataTable['cols'][] = array('id' => 'time_axis', 'label' => 'Time', 'type' => 'datetime');
$offset = 0;
foreach($sensors as $id => $description) {
//Add Line for Sensor
$new_column = array('id' => $id, 'label' => "$description ($id)", 'type' => 'number');
$dataTable['cols'][] = $new_column;
// Define your SQL statement //
$stm = $db->prepare('SELECT time, value FROM temperature WHERE sensor=:sensor AND time >= :starttime ORDER BY time');
$stm->bindValue(':sensor',$id,SQLITE3_TEXT);
$stm->bindValue(':starttime',$starttime,SQLITE3_INTEGER);
$result = $stm->execute();
$et = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
echo "</br>sql sensor $offset: $et </br>";
while($row = $result->fetchArray(SQLITE3_ASSOC)){
$date = $row['time']*1000;
$temp = $row['value'];
$cell = array();
$cell[] = array('v' => "Date($date)");
for ($i = 1; $i <= $offset; $i++) {
$cell[] = array('v' => null);
}
$cell[] = array('v' => $temp);
$dataTable['rows'][]['c'] = $cell;
}
$et = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
echo "</br>complete sensor $offset: $et </br>";
$offset++;
}
$json = json_encode($dataTable);
$et = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
echo "</br>done: $et </br>";
?>
I observed that iterating through the rows takes up to 1 seconds. There are ~7k entries total and the code runs on a raspberry pi.
get available sensors: 0.0048329830169678
sql sensor 0: 0.067873001098633
complete sensor 0: 1.0311329364777
sql sensor 1: 1.0555880069733
complete sensor 1: 1.2514669895172
done: 1.4120419025421
Is there anything i could do to reduce computation time significantly ?
Reference for the data format:
https://developers.google.com/chart/interactive/docs/php_example#exampleusingphphtml-file
https://developers.google.com/chart/interactive/docs/reference#dataparam

A simple approach to Infinite Scroll MySql Pulls

I'm having difficulty iterating through records while scrolling window. My initial thought was to load enough records to fit on screen then load an additional set when window scrolled to bottom. I've tried using session / variables to pass some counter to a function, no luck. The code below returns enough records to fit window height but with 0,10 limit. What would be a simple method to resolve this?
Another question is should I use LIMIT or ID > + LIMIT on the Mysql query?
$(function(){
setInterval(function(){
var totalHeight, currentScroll, visibleHeight;
if (document.documentElement.scrollTop)
{ currentScroll = document.documentElement.scrollTop; }
else
{ currentScroll = document.body.scrollTop; }
totalHeight = document.body.offsetHeight;
visibleHeight = document.documentElement.clientHeight;
if (totalHeight <= currentScroll + visibleHeight )
{
$.get('infinite_pull.php', function(data) {
$('body').append(data);
//alert('Load was performed.');
});
}
else
{
$('.dd').css('background-color','white');
}
}
, 100);
});
PHP
<?php
session_start();
mysql_connect('localhost','root','');
mysql_select_db('project5');
$query = "select user_email from users limit 0,10;";
$results= mysql_query($query);
while($row = mysql_fetch_array($results)){
echo $row['0'] . '<br/>';
}
?>
to call the php file multiple times sound bad,
all that overhead proberly worse then getting all at once.
can't you just calculate how many you need, and ask for that number?
<?php
$from = (int) $_GET['from'];
$count = (int) $_GET['count'];
mysql_connect('localhost','root','');
mysql_select_db('project5');
$query = "select user_email from users limit {$from},{$count};";
$results= mysql_query($query);
while($row = mysql_fetch_array($results)){
echo $row['0'] . '<br/>';
}
?>
i also think you should add an order by, to be sure the result always gets in the same order.
Use LIMIT, which combines a offset (1st param) and number of rows to get (2nd param). Here's a short example of pagination that get's the 7th page of a 100 numbers 7 at a time.
<?php
$arr = array();
for ( $x = 0; $x < 100; $x += 1 ) {
$arr[] = $x;
};
$page = 7;
$per_page = 7;
$current_page = 1;
for ( $z = 0; $z < count( $arr ); $z += 1 ) {
if ( 0 === ( $z % $per_page ) ) {
$current_page += 1;
}
if ( $current_page === $page ) {
$num_results = $current_page * $per_page;
$query = "select user_email from users limit {$num_results},{$per_page};";
echo "value $z on page $page via $query \n";
}
}
?>
Output:
$ php pagination.php
value 35 on page 7 via select user_email from users limit 49,7;
value 36 on page 7 via select user_email from users limit 49,7;
value 37 on page 7 via select user_email from users limit 49,7;
value 38 on page 7 via select user_email from users limit 49,7;
value 39 on page 7 via select user_email from users limit 49,7;
value 40 on page 7 via select user_email from users limit 49,7;
value 41 on page 7 via select user_email from users limit 49,7;

Categories

Resources