SQL SUM() values in model Joomla Component - php

I have this function
public function getItem($idOn = false)
{
if($idOn) {
$id = $idOn;
} else {
$id = JRequest::getInt('id', $idOn);
}
if(!$id) return false;
$select = $this->_db->getQuery(true);
$select->select('a.*, b.title AS categoryTitle, c.email AS userEmail, SUM(s.view_item) AS hits');
$select->from('#__cddir_content AS a');
$select->join('INNER','#__cddir_categories AS b ON a.categories_id = b.id');
$select->join('LEFT','#__users AS c ON a.users_id = c.id');
$select->join('LEFT','#__cddir_statistic as s ON a.id=s.item_id');
$select->where('a.id = '.$this->_db->quote($id));
$select->where('a.published = 1');
$user=JFactory::getUser();
$aclgroups = implode(',', $user->getAuthorisedViewLevels());
$select->where('a.access IN (' . $aclgroups . ')')
->where('b.access IN (' . $aclgroups . ')');
$this->_db->setQuery($select);
$item = $this->_db->loadObject();
return $item;
}
I need to sum again the hits that I already added "SUM(s.view_item) AS hits", because some items have the same alias (a.alias) in #__cddir_content
So I need first sum all the s.view_items as hit that have the same id
Then I have to sum the saved hits that have the same alias.
I hope I made myself clear
Thank you for you help

Related

display only if has group of numbers

I need to return list with prices only if there have groups i try already if else empty not !=
nothing help any suggestions ?
$usergroups = '11,9,10';
if (empty($usergroups)) {
return;
}
$fields = 'MIN(IF(prices.percentage_discount = 0, prices.price, prices.price - (prices.price * prices.percentage_discount)/100)) as price, prices.usergroup_id as usergroup_id, ud.usergroup as usergroup_name';
$condition = db_quote(' prices.product_id = ?i AND prices.usergroup_id IN (?p) AND ud.lang_code = ?s', $product['product_id'], $usergroups, DESCR_SL);
$group_by = 'usergroup_id';
$join = '?:usergroup_descriptions as ud ON ud.usergroup_id = prices.usergroup_id';
$opt_prices = db_get_array("SELECT ?p FROM ?:product_prices as prices LEFT JOIN ?p WHERE ?p GROUP BY ?p", $fields, $join, $condition, $group_by);
$currencies = Registry::get('currencies');
foreach ($opt_prices as &$price) {
$price['current'] = 0;
if (in_array($price['usergroup_id'], $auth['usergroup_ids'])) {
$price['current'] = 1;
$product['price'] = $price['price'];
}
$price['price'] = number_format($price['price'], 2, '.', ' ') . ' $';
}
$product['group_discounts'] = $opt_prices;
}
So i want display $product['group_discounts'] = $opt_prices;
only if there is $usergroups = '11,9,10';
Answer your comment:
You used that but ok here an example :
<?php
$usergroups = array('11','9','10');
$opt_prices='11';
if (in_array($opt_prices,$usergroups)){
echo 'yes';
}else{
echo 'no';
}
?>

variable not work in where clause php joomla

I have function and my function works good only I do not understand this:
<?php
// $category output is 23 when I echo $category; and there is no records
->where('d.category_id = ' . (int) $category)
// also this method not work
->where('d.category_id = ' . $category)
// but this method works
->where('d.category_id = 23')
?>
this is full code:
$category = $params->get('title');
//echo $category;
public static function getSuggested($category) {
$db = JFactory::getDBO();
$query = $db->getQuery(true);
//$now = $jdate->toSql();
//$nullDate = $db->quote($db->getNullDate());
$query->select('d.*');
$query->from('#__deals_deals AS d');
$query->select('c.title AS category_title');
$query->join('LEFT', '#__deals_categories AS c ON c.id = d.category_id')
->where('(d.is_market = 0 AND d.state = 1)','AND')
->where('d.category_id = 23')
->order('id DESC');
//$query->where('(d.publish_up = ' . $nullDate . ' OR d.publish_up <= ' . $query->quote($now) . ')');
//$query->where('(d.publish_down = ' . $nullDate . ' OR d.publish_down >= ' . $query->quote($now) . ')');
$db->setQuery($query,0,10);
$results = $db->loadObjectList();
return $results;
}
this function works good only need to get category data.
this is joomla module, and this function is in helper.php file in default.php file I am get some data from this function.
I found solution:
Add in mod_suggested_deals.php
$category = (int) $params->get('fieldvalue');
then:
$results = modsuggested_dealsHelper::getSuggested($category);
I found soluton for this question:
in my function I Add param $category
public static function getSuggested($category) {...}
in mod_suggested_deals.php I add code:
$category = $params->get('title');
then is code (it already was here).
$results = modsuggested_dealsHelper::getSuggested($category);
The mistake you are doing is you are defining a variable value outside a function but calling the variable inside it. If your class is not abstract class you can use $this->category or if your class is an abstract class then use the $category variable inside of the function like this
public static function getSuggested() {
$module = JModuleHelper::getModule('mod_yourmodulename');
$catid = new JRegistry($module->params);
$category = (int) $catid['title'];
$db = JFactory::getDBO();
$query = $db->getQuery(true);
//$now = $jdate->toSql();
//$nullDate = $db->quote($db->getNullDate());
$query->select('d.*');
$query->from('#__deals_deals AS d');
$query->select('c.title AS category_title');
$query->join('LEFT', '#__deals_categories AS c ON c.id = d.category_id')
->where('(d.is_market = 0 AND d.state = 1)','AND')
->where('d.category_id = '.$category)
->order('id DESC');
//$query->where('(d.publish_up = ' . $nullDate . ' OR d.publish_up <= ' . $query->quote($now) . ')');
//$query->where('(d.publish_down = ' . $nullDate . ' OR d.publish_down >= ' . $query->quote($now) . ')');
$db->setQuery($query,0,10);
$results = $db->loadObjectList();
return $results;
}

Search a MySQL table using multiple fields

I have this HTML form which has so many fields that someone can use to query data from MySQL table using multiple conditions. The form has select boxes, text boxes and check boxes, and date inputs.
I have this function which is ineffective
public function search(Request $request)
{
// loop through the defined fields
foreach($this->fields as $field){
// if the field is set and not empty
if(is_array($request->get($field))){
foreach ($request->get($field) as $value) {
$this->conditions[] = "`$field` = '" . $value . "'";
}
} else {
if(isset($_POST[$field]) && $request->get($field) != '') {
$data = $request->get($field);
if($field == 'bf_ref_no'){
$data = is_numeric( substr($request->get($field), 0, 2) ) ? 'BF'.$request->get($field) : $request->get($field) ;
}
$this->conditions[] = "`$field` = '" . $data . "'";
}
}
}
// builds the query
$query = "SELECT invoices.id as inv_id, invoices.created_at as inv_date, invoices.amount_paid, invoices.amount, csv_data_final.* FROM csv_data_final
LEFT JOIN invoices ON invoices.parent_id = csv_data_final.id ";
// if there are conditions defined
if(count($this->conditions) > 0) {
// append the conditions
$query .= "WHERE " . implode (' AND ', $this->conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
$results = DB::select( $query );
$borders = DB::table('borders')->orderBy('id', 'DESC')->get();
return view('track.track-withdata', compact('results', 'borders'));
}
This code doesn't work for dates using BETWEEN keyword.

Return values for appropriate arguments

Is here any possible to write single return for both $strValues and $strThumbImages i need to return $strValues for every time but returning $strThumbImages is just when it is available..
function doSelectBranchRecords($objArray,$ImageId = NULL)
{
global $global_config;
$strWhereClause = '';
if ($objArray['frmNameSearch']) {
$strWhereClause.= " AND A.branch_ident = '".$objArray['frmNameSearch']."' ";
}
if ($objArray['frmLoanSearch']) {
$strWhereClause.= " AND A.loan_ident = '".$objArray['frmLoanSearch']."' ";
}
if ($objArray['frmBeneficiarySearch']) {
$strWhereClause.= " AND A.beneficiary_idents = '".$objArray['frmBeneficiarySearch']."' ";
}
if ($objArray['frmDateSearch']) {
$strDate = explode("-", $objArray['frmDateSearch']);
$strAccountstarted = $strDate[2].'-'.$strDate[1].'-'.$strDate[0];
$strWhereClause.= " AND A.account_started = '".$strAccountstarted."' ";
/*printArray($strWhereClause); exit;*/
}
if ($ImageId) {
$strThumbImages = $global_config["SiteGlobalUploadPath"].$ImageId;
return $strThumbImages;
}
$strSqlSelect = "SELECT A.*,B.branch_name FROM tbl_companydetails as A,tbl_branchdetails as B where A.branch_ident=B.branch_id $strWhereClause order by company_id DESC";
$strValues = SelectQry($strSqlSelect);
return $strValues;
}
A php function can't return more than one variable. You could get both results from the function by returning an array with either one or two keys in it, then do a check in your calling code to see what has been set. So the end of your function becomes:
...
}
$output = array();
if ($ImageId) {
$strThumbImages = $global_config["SiteGlobalUploadPath"].$ImageId;
$output['thumbImages'] = $strThumbImages;
}
$strSqlSelect = "SELECT A.*,B.branch_name FROM tbl_companydetails as A,tbl_branchdetails as B where A.branch_ident=B.branch_id $strWhereClause order by company_id DESC";
$strValues = SelectQry($strSqlSelect);
$output['strValues'] = $strValues;
return $output;
}
#Simon and #Suchit are right in that you cannot return more than one variable. But in php it is very straightforwarded to return a list with multiple items like so:
function getXYZ(){
return array(4,5,6);
}
list($x,$y,$z) = getXYZ();
So in your case this could look like so:
$strThumbImages = null;
if ($ImageId) {
$strThumbImages = $global_config["SiteGlobalUploadPath"].$ImageId;
}
$strSqlSelect = "SELECT A.*,B.branch_name FROM tbl_companydetails as A,tbl_branchdetails as B where A.branch_ident=B.branch_id $strWhereClause order by company_id DESC";
$strValues = SelectQry($strSqlSelect);
return array($strValues, $strThumbImages);
As above #Simon Brahan said you can not return more than one variable.
so you can use array with different keys.but you should also check if $ImageId is set and not null.
if (isset($ImageId) && !is_null($ImageId)) {
$strThumbImages = $global_config["SiteGlobalUploadPath"].$ImageId;
$output['thumbImages'] = $strThumbImages;
}
$strSqlSelect = "SELECT A.*,B.branch_name FROM tbl_companydetails as A,tbl_branchdetails as B where A.branch_ident=B.branch_id $strWhereClause order by company_id DESC";
$strValues = SelectQry($strSqlSelect);
$output['strValues'] = $strValues;
return $output;

query with php array in mysql

I want to fetch contents with multiple filters, right now there's only one.
For Example:
SELECT * FROM Table1 WHERE status=true AND category = 'Camera' AND
model = 'Samsung' AND type = 'New'
I want to create an array for it. But as I'm a newbie in this one not getting a lead.
function getAllRequests($filter){
if(empty($filter)){
$addfilter = '';
}else{
$addfilter = 'AND cat_id=' . $filter;
}
}
$sql = 'SELECT * FROM Table1 WHERE status=true' . $filter;
Any help will be appreciated.
This will get you closer to the solution, though it will not replace the cat_id in the query, which will certainly be wrong - though impossible to do too much more without the array structure:
function getAllRequests($filter)
{
$addfilter="";
if(!empty($filter))
{
foreach($filter as $val)
{
$addfilter. = ' AND cat_id=' . $val .'\'';
}
}
return $addFilter;
}
$myFilters=getAllRequests($filter);
$sql = 'SELECT * FROM Table1 WHERE status=true' . $myFilters;
On the other hand, if your array is strucutred in a way like this:
array{ category => camera, model => samsung); // etc
you could use the following:
function getAllRequests($filter)
{
$addfilter="";
if(!empty($filter))
{
foreach($filter as $key => $val)
{
$addfilter. = " AND `$key` = '$val'";
}
}
return $addFilter;
}
$myFilters=getAllRequests($filter);
$sql = 'SELECT * FROM Table1 WHERE status=true' . $myFilters;
Edit: You can loop through all the filters in the following manner:
function getAllRequests()
{
$addfilter="";
if(!empty($_REQUEST))
{
foreach($_REQUEST as $key => $val)
{
$addfilter. = " AND `$key` = '$val'";
}
}
return $addFilter;
}
$myFilters=getAllRequests();
$sql = 'SELECT * FROM Table1 WHERE status=true' . $myFilters;
You don't need to pass the $_REQUEST (which will work for both GET and POST) as it already a superglobal.
function getAllRequests($filter){
if(empty($filter)){
$addfilter = '';
}else{
$addfilter = 'AND cat_id=' . $filter;
}
}
$sql = 'SELECT * FROM Table1 WHERE status=true' . $addfilter;
You can use another approach, which is using optional parameters and it will make your WHERE clause dynamic as you want. In this approach you pass all parameters' values directly to the sql query which should look like so:
SELECT *
FROM Table1
WHERE 1 = 1
AND (#status IS NULL OR status = #statusParam)
AND (#category IS NULL OR category = #categoryParam)
AND (#model IS NULL OR model = #modelParam)
AND (#type IS NULL OR type = #typeParam)
Then If any of the parameters #statusParam, #categoryParam, #modelParam or #typeParam passed to the query with NULL values, then the comparison with the column holding that value will be ignored. I used the predicate 1 = 1, in case all the values passed to the query with all NULL values in the case all the WHERE clause will be ignored as it won't presented, since WHERE 1 = 1 always true and it will be like SELECT * FROM Table1.
use this
function getAllRequests($filter){
if(empty($filter)){
$addfilter = '';
}else{
$addfilter .= 'AND cat_id=' . $filter;
}
return $addfilter;
}
$sql = 'SELECT * FROM Table1 WHERE status=true' . getAllRequests($filter);
When you are sending array make sure it has indexes
$conditions = array('category' => 'Camera', 'model' => 'Samsung' , 'type' => 'New')
Now loop through it. in your else condition
foreach($conditions as $key =>$value){
$addfilter .= 'AND ' . $key . ' = ' . $value;
}

Categories