There is a small problem. I have this 3 functions, and this functions make search in DB. But, that search give only one element from category (when we have 2 or more).
For example, if we have 1,2,3 searche give us only
1.
If we delete 1, it will be 2 and etc.
Any suggestions?
This is 3 functions
function displayList($clause) {
$clause = ' m.active=1 && g.active=1 && '.$clause;
$pageSize = 12;
$pageNo = isset($_GET['page'])? (int)$_GET['page']:0;
$qr = "SELECT count(DISTINCT m.id) FROM #tyregoods g, #tyremodels m WHERE m.id = g.owner_id && $clause";
$q = $this->execSQL($qr);
list($count) = $q->get();
$pageCount = ceil($count / $pageSize);
if (!$pageCount) $pageCount = 1;
if ($pageCount<=$pageNo) return false;
$offset = $pageNo * $pageSize;
list($sortV, $sort) = $this->getSort();
/*$q = $this->execSQL("SELECT m.id as modelid, m.icon, m.name, m.season, g.id, width, profile, diameter, studed, indx, side, remains, price
FROM #tyregoods g, #tyremodels m WHERE m.id = g.owner_id && $clause
ORDER BY $sortV LIMIT $pageSize OFFSET $offset ");*/
$q = "SELECT m.id as modelid, m.icon, m.name, m.season, g.id, width, profile, diameter, studed, indx, side, remains, price
FROM #tyregoods g, #tyremodels m WHERE m.id = g.owner_id && $clause GROUP BY m.id
ORDER BY $sortV LIMIT $pageSize OFFSET $offset";
$q = $this->execSQL($q);
$xml = '';
while ($data = $q->getAssoc()) {
$xml.=prop2xml($data);
}
return "<goodslist page='$pageNo' pagesize='$pageSize' pages='$pageCount' sort='$sort'>$xml</goodslist>";
}
function displayBySize() {
$params = $this->kernel->getModul('tyreparams');
$clause = $this->getSQLClause($params);
if ($clause['where'] == '') return '<noparams/>';
$xml = $this->displayList($clause).$params->display();
return "<search>$xml</search>";
}
function getSQLClause($params, $except = array()) {
$cl = array();
foreach($params->params as $id=>$param)
if ($param['value']!='' && !in_array($id, $except)){
$vl = trim($param['value']);
if ('vendor' == $id) {
$cl[] = "m.owner_id IN (SELECT ts.id FROM td_tyres ts WHERE ts.active=1 AND ts.id='$vl')";
}
else {
$pos = strpos($vl, '-');
if ($pos === 0) $pos = strpos($vl, '-', 1);
if ($pos) {
$lo = substr($vl, 0, $pos);
$hi = substr($vl, $pos + 1);
$t = "$id >= '$lo' && $id <= '$hi'";
}
else
$t = "$id = '$vl'";
if ($id == 'PCD') {
$t2 = str_replace('PCD', 'PCD2', $t);
$cl[] = "(($t) || ($t2))";
} else
$cl[] = $t;
}
}
return implode('&&', $cl);
}
UPD
SQL query -
SELECT m.id as modelid, m.icon, m.name, m.season, g.id, width, profile, diameter,
studed, indx, side, remains, price FROM td_tyregoods g, td_tyremodels m WHERE m.id =
g.owner_id && m.active=1 && g.active=1 && width = '245'&&profile = '50'&&m.owner_id IN
(SELECT ts.id FROM td_tyres ts WHERE ts.active=1 AND ts.id='13') GROUP BY m.id ORDER BY
name LIMIT 12 OFFSET 0
This query, give in mysql console exactly that we have at the site. Problem in query...
Related
I need help on some codes. This isn't made by me, i just copy a source code to make a website from another developer. I still don't know what is the problem although I have searched all the solutions online, because I am still learning.
<?php
$limit = 5;
$pagination = isset($_GET['pagination']) ? $_GET['pagination'] : "";
if (empty($pagination)) {
$position = 0;
$pagination = 1;
} else {
$position = ($pagination - 1) * $limit;
}
$query = $connect->execute("SELECT pinjam.id_peminjaman, pinjam.id_user,
user.nama_user, pinjam.id_ruang, ruang.nama_ruang, pinjam.id_hari,
hari.nama_hari, pinjam.tgl_pinjam, pinjam.jam_awal,
pinjam.jam_akhir, pinjam.keterangan, pinjam.status
FROM tbl_peminjaman AS pinjam
LEFT JOIN tbl_user AS user ON pinjam.id_user = user.id_user
LEFT JOIN tbl_ruang AS ruang ON pinjam.id_ruang = ruang.id_ruang
LEFT JOIN tbl_hari AS hari ON pinjam.id_hari = hari.id_hari
ORDER BY pinjam.updated_at DESC LIMIT $position, $limit");
$no = 1 + $position;
$check_search = $query->num_rows;
while ($query->fetch_object()) {
if ($data->status == 'DITERIMA') {
$color = "green-text";
} elseif ($data->status == 'DITOLAK') {
$color = "red-text";
} elseif ($data->status == 'MENUNGGU') {
$color = "yellow-text";
} else {
$color = "grey-text";
}
?>
Sorry, i haven't know yet how to modify the undetected variable. So please, help me. Thanks :)
Change this line
while ($query->fetch_object()) {
to this
while ($data = $query->fetch_object()) {
I hope I'm at the right place and that I did not copy too much of my code below - The code below will produce a report displaying ALL existing products from database - What I'm trying to achieve its to display just specific product (lets call them gid 1 and 2).
What I cannot wrap my head around ( maybe because I'm a network guy): I don't want to display certain product group, when I modify the SQL query, I'm able to remove the data ( amount$) but I want the entire Product category not to be display.
My question: is it more in the 'loop through product' that I need to change the code or in my SQL query ( I doubt) - and if you could tell me how to proceed.
Thank you to help me - I have close to 0 hours experience with PHP.
<?php
if (!defined("WHMCS"))
die("This file cannot be accessed directly");
$pmonth = str_pad((int)$month, 2, "0", STR_PAD_LEFT);
$reportdata["title"] = "Immobilier DD - Income by Product for ".$months[(int)$month]." ".$year;
$reportdata["description"] = "This report provides a breakdown per product/service of invoices paid in a given month. Please note this excludes overpayments & other payments made to deposit funds (credit), and includes invoices paid from credit added in previous months, and thus may not match the income total for the month.";
$reportdata["currencyselections"] = true;
$reportdata["tableheadings"] = array("Product Name","Units Sold","Value");
$products = $addons = array();
# Loop Through Products
$result = full_query("SELECT tblhosting.packageid,COUNT(*),SUM(tblinvoiceitems.amount) FROM tblinvoiceitems INNER JOIN tblinvoices ON tblinvoices.id=tblinvoiceitems.invoiceid INNER JOIN tblhosting ON tblhosting.id=tblinvoiceitems.relid INNER JOIN tblclients ON tblclients.id=tblinvoices.userid WHERE tblinvoices.datepaid LIKE '".(int)$year."-".$pmonth."-%' AND (tblinvoiceitems.type='Hosting' OR tblinvoiceitems.type='Setup' OR tblinvoiceitems.type LIKE 'ProrataProduct%') AND currency=".(int)$currencyid." GROUP BY tblhosting.packageid");
while ($data = mysql_fetch_array($result)) {
$products[$data[0]] = array("amount" => $data[2],"unitssold" => $data[1]);
}
# Loop Through Product Discounts
$result = full_query("SELECT tblhosting.packageid,COUNT(*),SUM(tblinvoiceitems.amount) FROM tblinvoiceitems INNER JOIN tblinvoices ON tblinvoices.id=tblinvoiceitems.invoiceid INNER JOIN tblhosting ON tblhosting.id=tblinvoiceitems.relid INNER JOIN tblclients ON tblclients.id=tblinvoices.userid WHERE tblinvoices.datepaid LIKE '".(int)$year."-".$pmonth."-%' AND tblinvoiceitems.type='PromoHosting' AND currency=".(int)$currencyid." GROUP BY tblhosting.packageid");
while ($data = mysql_fetch_array($result)) {
$products[$data[0]]["amount"] += $data[2];
}
# Loop Through Addons
$result = full_query("SELECT tblhostingaddons.addonid,COUNT(*),SUM(tblinvoiceitems.amount) FROM tblinvoiceitems INNER JOIN tblinvoices ON tblinvoices.id=tblinvoiceitems.invoiceid INNER JOIN tblhostingaddons ON tblhostingaddons.id=tblinvoiceitems.relid INNER JOIN tblclients ON tblclients.id=tblinvoices.userid WHERE tblinvoices.datepaid LIKE '".(int)$year."-".$pmonth."-%' AND tblinvoiceitems.type='Addon' AND currency=".(int)$currencyid." GROUP BY tblhostingaddons.addonid");
while ($data = mysql_fetch_array($result)) {
$addons[$data[0]] = array("amount" => $data[2],"unitssold" => $data[1]);
}
$total = 0;
$itemtotal = 0;
$firstdone = false;
$result = select_query("tblproducts","tblproducts.id,tblproducts.name,tblproductgroups.name AS groupname","","tblproductgroups`.`order` ASC,`tblproducts`.`order` ASC,`name","ASC","","tblproductgroups ON tblproducts.gid=tblproductgroups.id");
while($data = mysql_fetch_array($result)) {
$pid = $data["id"];
$group = $data["groupname"];
$prodname = $data["name"];
if ($group!=$prevgroup) {
$total += $itemtotal;
if ($firstdone) {
$reportdata["tablevalues"][] = array('','<strong>Sub-Total</strong>','<strong>'.formatCurrency($itemtotal).'</strong>');
$chartdata['rows'][] = array('c'=>array(array('v'=>$prevgroup),array('v'=>$itemtotal,'f'=>formatCurrency($itemtotal))));
}
$reportdata["tablevalues"][] = array("**<strong>$group</strong>");
$itemtotal = 0;
}
$amount = $products[$pid]["amount"];
$number = $products[$pid]["unitssold"];
$itemtotal += $amount;
if (!$amount) $amount="0.00";
if (!$number) $number="0";
$amount = formatCurrency($amount);
$reportdata["tablevalues"][] = array($prodname,$number,$amount);
$prevgroup = $group;
$firstdone = true;
}
$total += $itemtotal;
$reportdata["tablevalues"][] = array('','<strong>Sub-Total</strong>','<strong>'.formatCurrency($itemtotal).'</strong>');
$chartdata['rows'][] = array('c'=>array(array('v'=>$group),array('v'=>$itemtotal,'f'=>formatCurrency($itemtotal))));
$reportdata["tablevalues"][] = array("**<strong>Addons</strong>");
$itemtotal = 0;
$result = select_query("tbladdons","id,name","","name","ASC");
while($data = mysql_fetch_array($result)) {
$addonid = $data["id"];
$prodname = $data["name"];
$amount = $addons[$addonid]["amount"];
$number = $addons[$addonid]["unitssold"];
$itemtotal += $amount;
if (!$amount) $amount="0.00";
if (!$number) $number="0";
$amount = formatCurrency($amount);
$reportdata["tablevalues"][] = array($prodname,$number,$amount);
$prevgroup = $group;
}
$itemtotal += $addons[0]["amount"];
$number = $addons[0]["unitssold"];
$amount = $addons[0]["amount"];
if (!$amount) $amount="0.00";
if (!$number) $number="0";
$reportdata["tablevalues"][] = array('Miscellaneous Custom Addons',$number,formatCurrency($amount));
$total += $itemtotal;
$reportdata["tablevalues"][] = array('','<strong>Sub-Total</strong>','<strong>'.formatCurrency($itemtotal).'</strong>');
$chartdata['rows'][] = array('c'=>array(array('v'=>"Addons"),array('v'=>$itemtotal,'f'=>formatCurrency($itemtotal))));
$itemtotal = 0;
$reportdata["tablevalues"][] = array("**<strong>Miscellaneous</strong>");
$sql = "SELECT COUNT(*), SUM(tblinvoiceitems.amount)
FROM tblinvoiceitems
INNER JOIN tblinvoices ON tblinvoices.id=tblinvoiceitems.invoiceid
INNER JOIN tblclients ON tblclients.id=tblinvoices.userid
WHERE tblinvoices.datepaid LIKE '" . (int)$year . "-" . $pmonth . "-%' AND tblinvoiceitems.type='Item' AND currency=" . (int)$currencyid;
$result = full_query($sql);
$data = mysql_fetch_array($result);
$itemtotal += $data[1];
$number = $data[0];
$amount = $data[1];
if (!$amount) $amount="0.00";
if (!$number) $number="0";
$reportdata["tablevalues"][] = array('Billable Items',$number,formatCurrency($amount));
$result = full_query("SELECT COUNT(*),SUM(tblinvoiceitems.amount) FROM tblinvoiceitems INNER JOIN tblinvoices ON tblinvoices.id=tblinvoiceitems.invoiceid INNER JOIN tblclients ON tblclients.id=tblinvoices.userid WHERE tblinvoices.datepaid LIKE '".(int)$year."-".$pmonth."-%' AND tblinvoiceitems.type='' AND currency='$currencyid'");
$data = mysql_fetch_array($result);
$itemtotal += $data[1];
$reportdata["tablevalues"][] = array('Custom Invoice Line Items',$data[0],formatCurrency($data[1]));
$total += $itemtotal;
$reportdata["tablevalues"][] = array('','<strong>Sub-Total</strong>','<strong>'.formatCurrency($itemtotal).'</strong>');
$chartdata['rows'][] = array('c'=>array(array('v'=>"Miscellaneous"),array('v'=>$itemtotal,'f'=>formatCurrency($itemtotal))));
$total = formatCurrency($total);
$chartdata['cols'][] = array('label'=>'Days Range','type'=>'string');
$chartdata['cols'][] = array('label'=>'Value','type'=>'number');
$args = array();
$args['legendpos'] = 'right';
$reportdata["footertext"] = $chart->drawChart('Pie',$chartdata,$args,'300px');
$reportdata["monthspagination"] = true;
I try to use GroceryCRUD with SQL Server (2008 R2) to manage some table.
Well, I find the following thread very usefull on StackOverflow :
How can I run grocery with sql server?
But, when I use $this->grocery_crud->set_relation, it returns an error "PrimaryKey not found" on the method set_primary_key.
The table obviously has correctly set the primary key.
Can someone help me figure out where is the problem?
Ok. This is how I hack the code:
ref.version:
grocery-crud-1.5.2
CodeIgniter-3.0.1
STEP 1
File: system\database\drivers\pdo\subdrivers\pdo_sqlsrv_driver.php
Update method field_data($table)
public function field_data($table)
{
$sql = 'SELECT c.COLUMN_NAME, c.DATA_TYPE, c.CHARACTER_MAXIMUM_LENGTH, c.NUMERIC_PRECISION, c.COLUMN_DEFAULT
,CASE WHEN pk.COLUMN_NAME IS NOT NULL THEN 1 ELSE 0 END AS KeyType
FROM INFORMATION_SCHEMA.COLUMNS c
LEFT JOIN (
SELECT ku.TABLE_CATALOG,ku.TABLE_SCHEMA,ku.TABLE_NAME,ku.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS ku
ON tc.CONSTRAINT_TYPE = \'PRIMARY KEY\'
AND tc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME
) pk
ON c.TABLE_CATALOG = pk.TABLE_CATALOG
AND c.TABLE_SCHEMA = pk.TABLE_SCHEMA
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.COLUMN_NAME = pk.COLUMN_NAME
WHERE UPPER(c.TABLE_NAME) = '.$this->escape(strtoupper($table));
if (($query = $this->query($sql)) === FALSE)
{
return FALSE;
}
$query = $query->result_object();
$retval = array();
for ($i = 0, $c = count($query); $i < $c; $i++)
{
$retval[$i] = new stdClass();
$retval[$i]->name = $query[$i]->COLUMN_NAME;
$retval[$i]->type = $query[$i]->DATA_TYPE;
$retval[$i]->max_length = ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION;
$retval[$i]->primary_key = $query[$i]->KeyType;
$retval[$i]->default = $query[$i]->COLUMN_DEFAULT;
}
return $retval;
}
STEP 2
File: \system\database\drivers\sqlsrv\sqlsrv_driver.php
Update method field_data($table)
public function field_data($table)
{
$sql = 'SELECT c.COLUMN_NAME, c.DATA_TYPE, c.CHARACTER_MAXIMUM_LENGTH, c.NUMERIC_PRECISION, c.COLUMN_DEFAULT
,CASE WHEN pk.COLUMN_NAME IS NOT NULL THEN 1 ELSE 0 END AS KeyType
FROM INFORMATION_SCHEMA.COLUMNS c
LEFT JOIN (
SELECT ku.TABLE_CATALOG,ku.TABLE_SCHEMA,ku.TABLE_NAME,ku.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS ku
ON tc.CONSTRAINT_TYPE = \'PRIMARY KEY\'
AND tc.CONSTRAINT_NAME = ku.CONSTRAINT_NAME
) pk
ON c.TABLE_CATALOG = pk.TABLE_CATALOG
AND c.TABLE_SCHEMA = pk.TABLE_SCHEMA
AND c.TABLE_NAME = pk.TABLE_NAME
AND c.COLUMN_NAME = pk.COLUMN_NAME
WHERE UPPER(c.TABLE_NAME) = '.$this->escape(strtoupper($table));
if (($query = $this->query($sql)) === FALSE)
{
return FALSE;
}
$query = $query->result_object();
$retval = array();
for ($i = 0, $c = count($query); $i < $c; $i++)
{
$retval[$i] = new stdClass();
$retval[$i]->name = $query[$i]->COLUMN_NAME;
$retval[$i]->type = $query[$i]->DATA_TYPE;
$retval[$i]->max_length = ($query[$i]->CHARACTER_MAXIMUM_LENGTH > 0) ? $query[$i]->CHARACTER_MAXIMUM_LENGTH : $query[$i]->NUMERIC_PRECISION;
$retval[$i]->primary_key = $query[$i]->KeyType;
$retval[$i]->default = $query[$i]->COLUMN_DEFAULT;
}
return $retval;
}
STEP 3
File: \system\database\drivers\mssql\mssql_result.php
Update method field_data()
public function field_data()
{
$retval = array();
for ($i = 0, $c = $this->num_fields(); $i < $c; $i++)
{
$field = mssql_fetch_field($this->result_id, $i);
$retval[$i] = new stdClass();
$retval[$i]->name = $field->name;
$retval[$i]->type = $field->type;
$retval[$i]->max_length = $field->max_length;
$retval[$i]->primary_key = $field->primary_key;
}
return $retval;
}
That's all. I hope it can help other people.
I've been given this code to work with, and I know that mysql_* is deprecated, but I'm trying to figure out a way to join all of these queries, because these while loops and queries are hogging resources and killing load time. Any suggestions?
$result2 = mysql_query("SELECT * FROM tblOperators WHERE (Team = 'SALES' OR Team = 'RENEWALS' OR Team = 'CSR') AND OperatorLocale='USA' AND OperatorStatus='ACTIVE'");
while ($row2 = mysql_fetch_array($result2)) {
$operID = $row2['OperatorID'];
$result = mysql_query("SELECT * FROM tblUserPayments WHERE OperatorID = '$operID' AND PaymentStatus='OK' AND PaymentDate LIKE '$currentDate%'");
while ($row = mysql_fetch_array($result)) {
if ($row['PaymentReason'] == 'ACTIVATION') {
$ActvCount++;
if ($row['PaymentMethod'] == 'CREDITCARD' || $row['PaymentMethod'] == 'PAPERCHECK') {
$ActvUpgrade += $row['ChargeAmount'];
}
} elseif ($row['PaymentReason'] == 'UPGRADE') {
$userid = $row['UserID'];
$paymentdate = $row['PaymentDate'];
$result1 = mysql_query("SELECT * FROM tblRenewalInvoices WHERE UserID='$userid' AND ('$paymentdate' >= DATE_SUB(DueDate, INTERVAL 90 DAY) AND '$paymentdate' < DATE_ADD(DueDate, INTERVAL 15 DAY)) AND ParentInvoiceID IS NULL ORDER BY InvoiceNum DESC LIMIT 1");
if ($row1 = mysql_fetch_array($result1)) {
$packageid = $row['PackageID'];
$pack = mysql_query("SELECT * FROM tblUserPackages WHERE PackageID='$packageid';");
if ($pack1 = mysql_fetch_array($pack)) {
$expDate = $pack1['ExpirationDate'];
$dueDate = $row1['DueDate'];
$days = mysql_fetch_row(mysql_query("SELECT TO_DAYS('$expDate')-TO_DAYS('$dueDate');"));
$months = (int) (((int) $days + 14) / 30.4);
$years = (int) (((int) $days + 182) / 365);
$Intervals = 0;
if ($years > 0) {
$Intervals = $years;
} if (($pack1['Package'] or 'GPS-SVL') or ($pack1['Package'] == 'GPS-1') or ($pack1['Package'] == 'GPS-1PLUS')) {
if ($Intervals > 1) {
if ($row['PaymentMethod'] == 'CREDITCARD' || $row['PaymentMethod'] == 'PAPERCHECK') {
$renewalCount++;
$Actv += $row['ChargeAmount'];
}
} else {
if ($row['PaymentMethod'] == 'CREDITCARD' || $row['PaymentMethod'] == 'PAPERCHECK') {
$renewalCount++;
$ActvRenewal += $row['ChargeAmount'];
}
}
} else {
$renewalCount++;
$Actv += $row['ChargeAmount'];
}
} else {
}
} else {
if ($row['PaymentMethod'] == 'CREDITCARD' || $row['PaymentMethod'] == 'PAPERCHECK')
$ActvUpgrade += $row['ChargeAmount'];
}
} elseif ($row['PaymentReason'] == 'ADDVEHICLE') {
if ($row['PaymentMethod'] == 'CREDITCARD' || $row['PaymentMethod'] == 'PAPERCHECK')
$ActvVehicleAdds += $row['ChargeAmount'];
}
}
$result = mysql_query("SELECT * FROM tblRenewalCalls WHERE OperatorID = '$operID' AND PayStatus='OK' AND DateSubmitted LIKE '$currentDate%'");
while ($row = mysql_fetch_array($result)) {
if ($row['Charged']) {
if ((int) $row['RenewYears'] > 1) {
$renewalCount++;
$Actv += $row['RenewTotal'];
} else {
$renewalCount++;
$ActvRenewal += $row['RenewTotal'];
}
}
}
} if ($ActvCount != 0) {
$PerActv = ($ActvUpgrade + $ActvVehicleAdds) / $ActvCount;
} else {
$PerActv = 0;
}
$total = $Actv + $ActvRenewal + $ActvUpgrade + $ActvVehicleAdds;
// Fix to show proper renewal dollars
$ActvRenewal = $total - ($ActvVehicleAdds + $ActvUpgrade);
$AvgRenewal = ($ActvRenewal) / $renewalCount;
$upgradeEarned = $ActvUpgrade;
$renewalEarned = $ActvRenewal;
Here is my code so far for the joined query, but it's not correct because I am still missing certain bits of information. It is much faster for mysql to handle the mathematics, than for the database to pass the information to php, then have php process it. I'm just not sure as to how to approach this:
$result = mysql_query(
"SELECT p.PaymentReason AS PaymentReason,
p.PaymentMethod AS PaymentMethod,
p.ChargeAmount AS ChargeAmount,
p.UserID AS UserID,
p.PaymentDate AS PaymentDate,
r.PackageID AS PackageID
FROM tblOperators AS o JOIN tblUserPayments AS p JOIN tblRenewalInvoices
AS r JOIN tblUserPackages AS k JOIN tblRenewalCalls
AS c ON o.OperatorID=p.OperatorID
AND r.UserID=p.UserID AND r.PaymentDate=p.PaymentDate
AND r.PackageID=k.PackageID
WHERE (o.Team='SALES' OR o.Team='RENEWALS' OR o.Team='CSR') AND
o.OperatorLocale='USA' AND
o.OperatorStatus='ACTIVE' AND
p.PaymentStatus='OK' AND
p.PaymentDate LIKE '$currentDate%'");
Any help is greatly appreciated.
Try this:: You have missed the JOIN Criteria for Table tblRenewalCalls
SELECT p.PaymentReason AS PaymentReason,
p.PaymentMethod AS PaymentMethod,
p.ChargeAmount AS ChargeAmount,
p.UserID AS UserID,
p.PaymentDate AS PaymentDate,
r.PackageID AS PackageID
FROM tblOperators AS o
JOIN tblUserPayments AS p ON o.OperatorID=p.OperatorID
JOIN tblRenewalInvoices AS r ON r.UserID=p.UserID AND r.PaymentDate=p.PaymentDate
JOIN tblUserPackages AS k ON r.PackageID=k.PackageID
JOIN tblRenewalCalls AS c // JOIN CRITERIA
WHERE (o.Team='SALES' OR o.Team='RENEWALS' OR o.Team='CSR') AND
o.OperatorLocale='USA' AND
o.OperatorStatus='ACTIVE' AND
p.PaymentStatus='OK' AND
p.PaymentDate LIKE '$currentDate%'")
I have a function that should calculate prices based on quantity.
The function should loop through every order and calculate every product price based on quantity, then should return order total price.
What i'm doing wrong?
public function getSumaComanda($cos) {
$suma = $this->_db->query(sprintf("SELECT (#pretredus:=`pretredus`) AS `pretredus`,(CASE #pretredus WHEN 0 THEN `prettotal` ELSE `pretredus` END) AS `prettotal` , cantitate FROM comenzi WHERE cos = '%d'", $cos));
$suma->execute();
$data_array = $suma->fetchAll(PDO::FETCH_ASSOC);
$count = $this->_db->query(sprintf("SELECT COUNT(*) FROM cosuri WHERE id='%d'", $cos));
$num = $count->fetchColumn();
for ($x = 0; $x < $num; $x++) {
$price = $data_array['cantitate'][$x] * $data_array['prettotal'][$x];
$pret = $pret + $price;
$pret = number_format($pret, 2, ".", "");
}
$rez = $pret;
return $rez . ' Lei';
}
You should learn how to basically debug your variables. With using var_dump($data_array); you can see, what's in there.
You have to use the numerical index first:
$price = $data_array[$x]['cantitate'] * $data_array[$x]['prettotal'];
Nevertheless, your second query is useless. You don't have to count the results and can use instead a while-loop:
public function getSumaComanda($cos) {
$suma = $this->_db->query(sprintf("SELECT (#pretredus:=`pretredus`) AS `pretredus`,(CASE #pretredus WHEN 0 THEN `prettotal` ELSE `pretredus` END) AS `prettotal` , cantitate FROM comenzi WHERE cos = '%d'", $cos));
$suma->execute();
while ($data_array = $suma->fetch(PDO::FETCH_ASSOC)) {
$pret += $data_array['cantitate'] * $data_array['prettotal'];
}
return number_format($pret, 2, ".", "") . ' Lei';
}