Combine results for SQL query - php

I am in a bit of a pinch. I am using WHMCS and building a custom report but am running into trouble with one of my queries. Here is an overview:
I have 2 tables; tblinvoices which has the subtotal, tax, total, etc. of the invoice and tblinvoiceitems which has the individual line items that appear on the invoice. I am wanting to run a query that returns all of the individual line items and their price which I have been able to do. I run into problems when I do 'GROUP BY' and group the results by invoice numder, then it only returns the first line item for each invoice. I want to group them by invoice number so it only has 1 line in the report. Here is my query:
$query = "SELECT date_format(tblinvoices.datepaid,'%m-%d-%Y') AS datepaid,
tblinvoices.userid,
tblinvoices.id,
tblinvoices.subtotal,
tblinvoices.credit,
tblinvoices.tax,
tblinvoices.tax2,
tblinvoices.total,
tblinvoices.taxrate,
tblinvoices.taxrate2,
tblinvoiceitems.description,
tblinvoiceitems.amount,
tblinvoices.status,
FROM tblinvoices
INNER JOIN tblinvoiceitems ON tblinvoices.id = tblinvoiceitems.invoiceid
GROUP BY tblinvoices.id";
$result = mysql_query($query);
# Math Operations
$statement = array();
$count = 0;
if ($result !== false) {
while ($data = mysql_fetch_object($result)) {
$invoiceid = $data->id;
$datepaid = $data->datepaid;
$description = $data->description;
$item_amount = $data->item_amount;
$subtotal = $data->subtotal;
$credit = $data->credit;
$tax = $data->tax;
$tax2 = $data->tax2;
$total = $data->total;
if ($export != true) {
$client_link = '<a href=clientssummary.php?userid='.$data->userid.'>'.$data->userid;
$invoice_link = '<a href=invoices.php?action=edit&id='.$data->id.'>'.$data->id;
}
else {
$client_link = $data->userid;
$invoice_link = $data->id;
}
if (strpos($description, 'Setup') !== false) {
$setup = $item_amount;
}
else {
$setup = 0;
}
if (strpos($description, 'Addon') !== false) {
$addon = $item_amount;
}
else {
$addon = 0;
}
if (strpos($description, 'Tax Guide: No => Yes') !== false) {
$taxguide = $item_amount;
}
else {
$taxguide = 0;
}
if (strpos($description, 'Reading Rack Bundle') !== false) {
$reading = $item_amount;
}
else {
$reading = 0;
}
if (strpos($description, 'Toolkit Bundle') !== false) {
$toolkit = $item_amount;
}
else {
$toolkit = 0;
}
$hosting = $subtotal - $setup - $addon - $taxguide - $reading - $toolkit;
$statement[$invoiceid."_".$count] = array($datepaid,$client_link,$promo,$dtn,$company,$state,$invoice_link,$setup,$addon,$taxguide,$reading,$toolkit,$hosting,$subtotal,$credit,$tax+$tax2,$total);
$count++;
}
}
foreach ($headings AS $k=>$v) {
$reportdata["tableheadings"][] = $v;
}
//ksort($statement);
foreach ($statement AS $invoiceid=>$entry) {
$reportdata["tablevalues"][] = array(
$entry[0], // datepaid
$entry[1], // clientid
$entry[2], // promocode
$entry[3], // dtn
$entry[4], // companyname
$entry[5], // state
$entry[6], // invoiceid
formatCurrency($entry[7]), // setup
formatCurrency($entry[8]), // addon
formatCurrency($entry[9]), // taxguide
formatCurrency($entry[10]), // reading
formatCurrency($entry[11]), // toolkit
formatCurrency($entry[12]), // hosting
formatCurrency($entry[13]), // subtotal
formatCurrency($entry[14]), // credit
formatCurrency($entry[15]), // tax
formatCurrency($entry[16]) // total
);
}
mysql_free_result($result);
I will be happy to provide any additional information/code if it helps. I though this might be a more general type question...thanks!

With the result you are describing your result set would look like:
userid | id | subtotal | credit | tax | status | desc | amount
______________________________________________________________
1 | 1 | 20 | 0 | .7 | 1 | item1| 10
1 | 1 | 20 | 0 | .7 | 1 | item2| 10
1 | 2 | 30 | 0 | 2.1 | 1 | item3| 15
1 | 2 | 30 | 0 | 2.1 | 1 | item3| 15
1 | 3 | 10 | 0 | .7 | 0 | item1| 10
1 | 4 | 1 | 0 | .07 | 0 | item4| 1
Is this what you are looking for?

So try group by invoice.id and invoice.userid, and then maybe invoice.subtotal....
May run into some issues if you later decide to aggregate anything but this should do it.

Related

laravel add amount to the next parent in loop

I have a loop which will get the parent of a user but only up to the max user rank which is Senior.
My question is how to add the amount assigned to a user rank if he is not/skipped in the loop or no record found for that rank.
The code below is working and inserting the earnings to each rank, because the parents ranks are present in the database. But what if some is not, I want to add the amount of that user who is not in the loop-to the next rank.
Imagine that it is looping through the parent until it gets to Senior, that's how it works.
The rank are in order
Junior
Premium
Advanced
Senior
Ranks with their corresponding amount value
Junior - 100
Premium - 150
Advanced - 200
Senior - 250
Users table
+------+------------+-------------+------------+
| id | username | parent_id | rank |
+------+------------+-------------+------------+
| 1 | john | NULL | Senior |
| 2 | jane | 1 | Advanced |
| 3 | josh | 2 | Premium |
| 4 | joey | 3 | Junior |
| 5 | jade | 4 | Basic |
+----------------------------------------------+
Code
$user_id = 5; // jade
$parent_id = 4;
// call the function to insert the earnings
self::insertEarnings($user_id,$parent_id);
private function insertEarnings($user_id,$parent_id) {
if ($parent_id > 0) {
$user_parent = $parent_id;
$has_parent = true;
// start iteration
while($has_parent == true){
$account = User::where('id',$user_parent)->first();
$amount = 0;
if ($account->rank == "Junior" ) {
$amount = 100;
} elseif ($account->rank == "Premium") {
$amount = 150;
// for example this user/parent does not exist the amount(150) for him will be added to the next rank which is the Advance
} elseif ($account->rank == "Advanced") {
$amount = 200;
} elseif ($account->rank == "Senior") {
$amount = 250;
// set to false to stop the iteration
$has_parent = false;
}
$earnings = new Earnings;
$earnings->user_id = $account->id;
$earnings->amount = $amount;
$earnings->save();
$next_parent = User::where('id',$user_parent)->first();
$user_parent = $next_parent->parent_id;
if($user_parent == 0){
$has_parent = false;
}
}
}
}
Edit:
The $user_id is not used in this example, but there's a use to that that didn't included in the question because that is not the main problem.

laravel iteration adding amount on parent

I mean, I have a referral system which is every parent_id has parent and the parent_id of that parent until it gets to the last parent which is the Senior.
Given that a user has purchased an item and it is successful, now I am calling the insertEarnings function to insert the corresponding amount to his parent_id, if his parent_id is Junior his parent_id will get 100.
This is how the question begin, what if his parent doesn't have a rank meaning not active, the amount to be insert to his parent_id will go through the next rank which is the Premium so the Premium will no have 250 total, after that proceed the normal insertion of the amount to the parent_id of Premium which is the Advanced- he will get the corresponding amount which is 200, because the rank below him which is the Premium is existing, the insertion will go through until it gets to the last rank which is the Senior
Imagine that it is looping through the parent until it gets to the last rank - Senior.
The ranks are in order
Junior
Premium
Advanced
Senior
Ranks with their corresponding amount value
Junior - 100
Premium - 150
Advanced - 200
Senior - 250
Users table
+------+------------+-------------+------------+
| id | username | parent_id | rank |
+------+------------+-------------+------------+
| 1 | john | NULL | Senior |
| 2 | jane | 1 | Advanced |
| 3 | josh | 2 | Premium |
| 4 | joey | 3 | Junior |
| 5 | jade | 4 | Basic |
+----------------------------------------------+
Code
$user_id = 5; // jade
$parent_id = 4;
// call the function to insert the earnings
self::insertEarnings($user_id,$parent_id);
private function insertEarnings($user_id,$parent_id) {
if ($parent_id > 0) {
$user_parent = $parent_id;
$has_parent = true;
// start iteration
while($has_parent == true){
$account = User::where('id',$user_parent)->first();
$amount = 0;
if ($account->rank == "Junior" ) {
$amount = 100;
} elseif ($account->rank == "Premium") {
$amount = 150;
// for example this user/parent does not exist the amount(150) for him will be added to the next rank which is the Advance
} elseif ($account->rank == "Advanced") {
$amount = 200;
} elseif ($account->rank == "Senior") {
$amount = 250;
// set to false to stop the iteration
$has_parent = false;
}
$earnings = new Earnings;
$earnings->user_id = $account->id;
$earnings->amount = $amount;
$earnings->save();
$next_parent = User::where('id',$user_parent)->first();
$user_parent = $next_parent->parent_id;
if($user_parent == 0){
$has_parent = false;
}
}
}
}
The $user_id is not used in this example, but there's a use to that that didn't included in the question because that is not the main problem.

How to update multiple rows in php mysql

I have some code to update multiple row in php mysql like this.
<?php
$idOrder = $_GET['idOrder'];
$conn = new MySQLi('localhost','root','','project_ecommerce');
$query_select = "SELECT status FROM order_product WHERE id_order='".$idOrder."'";
$sql_select = $conn->query($query_select);
$result_select = $sql_select->fetch_assoc();
$status ='';
if ($result_select['status'] == 0) {
$status .= 1;
}else{
$status .= 0;
}
$query_update = "UPDATE order_product SET status='".$status."' WHERE id_order='".$idOrder."'";
$sql_update = $conn->query($query_update);
if ($sql_update == TRUE) {
$query_select_product = "SELECT order_product.id_product AS ID_PRD, order_product.status AS STATUS, order_product.qty AS QTY_ORD, products.stock AS STOCK FROM order_product JOIN products ON order_product.id_product = products.id_product WHERE order_product.id_order ='".$idOrder."'";
$sql = $conn->query($query_select_product);
$result = $sql->fetch_all(MYSQLI_ASSOC);
$stock_update='';
for ($i=0; $i < count($result); $i++) {
if ($result[$i]['STATUS'] == 0) {
$stock_update .= ($result[$i]['STOCK']+$result[$i]['QTY_ORD']);
}else{
$stock_update .= ($result[$i]['STOCK']-$result[$i]['QTY_ORD']);
}
$update_product = "UPDATE products SET stock='".$stock_update."' WHERE id_product='".$result[$i]['ID_PRD']."'";
$sql_update_product = $conn->query($update_product);
}
}
echo $idOrder;
?>
if status updated to 1 i give result like this:
+----------------+-------+
| id_product | stock |
+----------------+-------+
| PRD-0416-17-1 | 100 |
| PRD-0416-17-10 | 100 |
| PRD-0416-17-11 | 98 |
| PRD-0416-17-12 | 9898 |
+----------------+-------+
And if status updated to 0 i give result like this:
+----------------+---------+
| id_product | stock |
+----------------+---------+
| PRD-0416-17-1 | 100 |
| PRD-0416-17-10 | 100 |
| PRD-0416-17-11 | 100 |
| PRD-0416-17-12 | 1009900 |
+----------------+---------+
How i can fix it ?
You're using .= in these assignments, which concatenates the results from the previous row to the previous value of $stock_update. They should just be =.
if ($result[$i]['STATUS'] == 0) {
$stock_update = ($result[$i]['STOCK']+$result[$i]['QTY_ORD']);
}else{
$stock_update = ($result[$i]['STOCK']-$result[$i]['QTY_ORD']);
}
This entire thing could be done in a single query:
UPDATE order_product AS o
JOIN product AS p ON o.id_product = p.id_product
SET o.status = NOT o.status,
p.stock = IF(o.status = 0, p.stock + o.qty_ord, p.stock - o.qty_ord)
WHERE o.id_order = $idOrder

Combine csv column values in PHP

I have a csv file with 5 rows :
id | price| name | sku | qty
1 | 22 | widget0 | abcd | 1
2 | 21 | widget1 | efgh | 1
3 | 10 | widget0 | abcd | 2
4 | 44 | widget1 | efgh | 1
5 | 22 | widget4 | mnop | 1
etc...
The first 3 columns are just here for visual purpose and are not used for what I need to achieve.
What I need to do is read the sku and qty data in the file and output the result.
I have to count the number of the same skus and get the total qty per sku.
Based on the example above, I need :
sku | qty
abcd | 3
efgh | 2
ijkl | 1
mnop | 1
With the following code, I can get the total number of the same skus in the file :
$file = ('my.csv');
$fh = fopen($file, 'rb');
$tag = array();
$qty = array();
$row=1;
while($col = fgetcsv($fh)) {
if($row == 1){ $row++; continue; } //skip 1st row
$num = count($fh);
if (isset($tag[$col[3]])) {
$tag[$col[3]]++;
}
else {
$tag[$col[3]] = 1;
}
}
print_r($tag);
It gives me :
sku | qty
abcd | 2
efgh | 2
ijkl | 1
mnop | 1
Which is not correct. I don't know how to get the qty column value and associate it to the total number of skus value in the csv file.
Any thoughts ?
Use below code for your solution
$file = ('my.csv');
$fh = fopen($file, 'rb');
$tag = array();
$qty = array();
$row=1;
while($col = fgetcsv($fh)) {
if($row == 1){ $row++; continue; } //skip 1st row
$num = count($fh);
if (isset($tag[$col[3]])) {
//$tag[$col[3]]++;
$tag[$col[3]] = (int)$tag[$col[3]] + (int)$col[4]; // where $col[4] = qty with forcing to `int` value
}
else {
$tag[$col[3]] = $col[4];
}
}
print_r($tag);
you need to make SUM of quantity instead just increase with +1
Hope this will help!
try this solution
$file = ('my.csv');
$fh = fopen($file, 'rb');
$tag = array();
$qty = array();
$row=1;
//skip first row
fgetcsv($fh, 10000, ",");
while($col = fgetcsv($fh,10000)) {
$num = count($fh);
if (isset($tag[$col[3]])) {
$tag[$col[3]]++;
}
else {
$tag[$col[3]] = 1;
}
}
print_r($tag);

in MYSQL, get only those columns that have values that are the same

I have a table showing what pieces of a puzzle a user has in Boolean like...
client | col A | col B | col C | col D | col E
john Doe | 1 | 1 | 0 | 0 | 1
Jane Deer| 0 | 1 | 0 | 1 | 0
And I can grab the row from the Db.
// Get puzzle pieces
$requery = "SELECT * FROM puzzletbl WHERE client_id = '$client_id' LIMIT 1";
$reresult = mysqli_query($dbc, $requery);
// Check for missing pieces
if ($reresult){
while ($row = mysqli_fetch_array($reresult, MYSQLI_ASSOC)) {
$status = array("NO", "OKAY");
} // END WHILE
} // END IF REresult
I need to get only those columns with 0 (they are missing piece) so I can add that to an email letting them know what is missing.
Loop through $row, and test whether the value is 0.
while ($row = mysqli_fetch_array($reresult, MYSQLI_ASSOC)) {
$zero_cols = array();
foreach ($row as $col => $val) {
if ($col == "client") {
$client = $val;
} elseif ($val == 0) {
$zero_cols[] = $col;
}
}
// Send mail to $client with $zero_cols info
}

Categories