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.
Related
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'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%'")
$t_enquirys_big_total = 0;
for ($i=0; $i<$totaldept; $i++){
$name = $v_ud_name[$i];
$querytotal = "SELECT category, user_dept_name
FROM $t_bug_table
WHERE team_id = '$t_team' && user_dept_name = '$name' && date_submitted BETWEEN '$t_start_string2' AND '$t_end_string2'";
$resulttotal = db_query ($querytotal);
while ($rowtotal = db_fetch_array ($resulttotal)){
$t_enquirys_big_total++;
}
}
for ($i=0; $i<$totaldept; $i++){
$name = $v_ud_name[$i];
$querybug = "SELECT category, user_dept_name
FROM $bug_table
WHERE team_id = '$t_team' && user_dept_name = '$name' && date_submitted BETWEEN '$t_start_string2' AND '$t_end_string2'";
$resultbug = db_query ($querybug);
$t_enquirys_total = 0;
$t_aenquirys = 0;
$t_complaint = 0;
$t_general = 0;
$t_request = 0;
$t_dailywork = 0;
$t_enguiry_count[$v_det_id[$i]] = 0;
$t_complaint_count[$v_det_id[$i]] = 0;
$t_general_count[$v_det_id[$i]] = 0;
$t_request_count[$v_det_id[$i]] = 0;
$t_dailywork_count[$v_det_id[$i]] = 0;
$t_aenquirys_total = 0;
$t_complaint_total = 0;
$t_general_total = 0;
$t_request_total = 0;
$t_dailywork_total = 0;
$t_aenquirys_total_perc = 0;
$t_complaint_total_perc = 0;
$t_general_total_perc = 0;
$t_request_total_perc = 0;
$t_dailywork_total_perc = 0;
$t_cat_total[$v_ud_id[$i]] = 0;
$t_all_cat_total = 0;
$t_enquiry_val = 'Enquiry';
$t_complaint_val = 'Complaint';
$t_general_val = 'General';
$t_request_val = 'Request';
$t_dailywork_val = 'Daily Work';
while ($rowbug = db_fetch_array ($resultbug)){
$t_enquirys_total++;
switch( $rowbug['category'] ) {
case $t_enquiry_val:
$t_aenquirys++;
$t_enguiry_count[$v_ud_id[$i]]++;
break;
case $t_complaint_val:
$t_complaint++;
$t_complaint_count[$v_ud_id[$i]]++;
break;
case $t_general_val:
$t_general++;
$t_general_count[$v_ud_id[$i]]++;
break;
case $t_request_val:
$t_request++;
$t_request_count[$v_ud_id[$i]]++;
break;
case $t_dailywork_val:
$t_dailywork++;
$t_dailywork_count[$v_ud_id[$i]]++;
break;
}
}
$t_cat_total[$v_ud_id[$i]] = $t_enguiry_count[$v_ud_id[$i]] + $t_complaint_count[$v_ud_id[$i]] + $t_general_count[$v_ud_id[$i]] + $t_request_count[$v_ud_id[$i]] + $t_dailywork_count[$v_ud_id[$i]];
$t_ud_total_perc[$v_ud_id[$i]] = number_format((($t_cat_total[$v_ud_id[$i]] / $t_enquirys_big_total) * 100), 2);
This is the half of the function that i use to retrieve data and also to calculate the percentage.When i try to use $querytotal,it indeed print out the data, but the second $querytotal below it does not show the data..please help
The thing happens because my execution time is 30sec. After add this particular code, it works fine.ini_set("max_execution_time", 0);
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...
My SQL query is based on data provided.
For example :
// table
$table = new Model_MyTable_DbTable();
// data
$columns = array( 'column1', 'column2', 'column3' );
// query
$select = $table->select();
$select->where('deleted = ?', '0' );
for( $i = 0; $i < count( $columns ); $i++ ) {
if( $i == 0 ) {
$select->where( $columns[$i] . ' > ?', '0' );
} else {
$select->orWhere( $columns[$i] . ' > ?', '0' );
}
}
$select->where('disabled = ?', '0' );
// print query
echo $select->assemble();die();
Above code result into following query:
SELECT `mytable`.* FROM `mytable` WHERE
(deleted = '0') AND
(column1 > '0') OR (column2 > '0') OR (column3 > '0') AND
(disabled = '0')
But I want something like this:
SELECT `mytable`.* FROM `mytable` WHERE
(deleted = '0') AND
(column1 > '0' OR column2 > '0' OR column3 > '0') AND
(disabled = '0')
How it is possible ?
Thanks
I think this should do the job:
// table
$table = new Model_MyTable_DbTable();
// data
$columns = array('column1', 'column2', 'column3');
// query
$select = $table->select();
$select->where('deleted = ?', '0');
$myOrParts = array();
for ($i = 0; $i < count($columns); $i++) {
$myOrParts []= $table->getAdapter()->quoteInto($columns[$i] . ' > ?', '0');
}
$myWhere = implode(' OR ', $myOrParts);
$select->where(new Zend_Db_Expr($myWhere));
$select->where('disabled = ?', '0');
// print query
echo $select->assemble();
die();