Link to home
Start Free TrialLog in
Avatar of majdolyan
majdolyanFlag for Saudi Arabia

asked on

Modify mysql statement in php code

The attached PHP code display all users of a mysql table, I want to make a modification and sort displayed names automatically by "item_amt". This is not a column name but it's a calculated value using Count function.

There are two tables involved here: Ad (for ads details, including userid for each ad) & User (for user details).

Any help is appreciated?
if(!defined('SITE_PATH')) die('Access denied');
 
function Members_List_main(){
global $db,$MOD_CFG,$DATE_TIME_FMT; // all globals here
 
//nav stuff starts
 
 $whitelist = array(
   'search_by' => array(
     'type' => 'alpha',
   ),
   'sort_by' => array(
     'type' => 'alpha',
   ),
   'a_d' => array(
     'type' => 'option',
     'options' => array('asc', 'desc'),
   ),
   'off' => array(
     'type' => 'int',
   ),
   'q' => array(
     'type' => 'string',
   ),
 );
 
 $clean = esFilter($_GET, $whitelist);
 
if(!$clean['off'] || $_SERVER['REQUEST_METHOD']=='POST') $clean['off'] = 0;
if(!$clean['a_d']) $clean['a_d'] = 'asc';
 
$num = $clean['off']*$MOD_CFG['DISP_ROWS'];
 
$ql = 'SELECT COUNT(*) FROM '.TBL_USER.' WHERE 1';
 
 $sel_search_by = array(
   'username' => '{Username}',
 );
 
$add_url = '';
 
if($_GET['s_res']) {
  
  if($clean['search_by'] && $sel_search_by[$clean['search_by']] && $clean['q']) {
    $ql.=' AND '.$clean['search_by']." LIKE '%".addcslashes($db->quote($clean['q']), '%_')."%'";
  }
  if($clean['sort_by']) {
    $ql.=' ORDER BY "'.$clean['sort_by'].'" '.$clean['a_d'];
  }
  $add_url='&s_res=1';
  if($clean['search_by'] && $clean['q']) $add_url.='&search_by='.$clean['search_by'].'&q='.urlencode($clean['q']);
  if($clean['sort_by']) $add_url.='&sort_by='.$clean['sort_by'].'&a_d='.$clean['a_d'];
}
 
$numrecs = $db->one_data($ql);
 
$lower = $num+1;
if($lower>$numrecs) $lower = 0;
$upper = $num+$MOD_CFG['DISP_ROWS'];
if($upper>$numrecs) $upper = $numrecs;
 
$ql = str_replace('COUNT(*)','id,username,UNIX_TIMESTAMP(regdate) AS regdate',$ql);
if($MOD_CFG['DISP_ROWS']) $ql.=" LIMIT $num,".$MOD_CFG['DISP_ROWS'];
 
$tpl = &new HawkTpl;
$tpl->InitArray('row');
 
$O_UFS = &Factory::singleton('FieldsSet', '{user_fields}');
 
$res = $db->query($ql);
 
if(mysql_num_rows($res)>0){
 
  $A_UID = array();
  
  while($v = mysql_fetch_assoc($res)) $A_UID[] = $v['id'];
  
  $A_ONLINE = IsUserOnline($A_UID);
  $A_ITEMS = $db->two_col_assoc('SELECT userid,COUNT(*) FROM '.TBL_AD.' WHERE userid IN('.implode(',',$A_UID).') GROUP BY userid');
  
  mysql_data_seek($res,0);
  
  while($v = mysql_fetch_assoc($res)){
    /*
    $v = $O_UFS->FillCustomFieldsArray($v); 
    $O_UFS->AdjustCustomFields($v);
    */
    $v['num'] = ++$num;
    $v['online'] = $A_ONLINE[$v['id']];
    $v['item_amt'] = $A_ITEMS[$v['id']];
    if(!$v['item_amt']) $v['item_amt'] = 0;
    $v['regdate'] = strftime($DATE_TIME_FMT,$v['regdate']);
    $tpl->AddCell('row',$v);
  }
}
 
$tpl_v = compact('numrecs','lower','upper');
$tpl_v['nav'] = GetNavigation(HW_MOD_URL,$MOD_CFG['DISP_ROWS'],10,$numrecs,$clean['off'],$add_url);
//nav stuff ends
 
 $tpl_v['search_by'] = GetAdmSel($sel_search_by, $clean['search_by']);
 
 $a_v = array(
   'username'=>'{Username}',
   'regdate'=>'{Date_Reg}',   
 
 
 );
 
 $tpl_v['sort_by'] = GetAdmSel($a_v, $clean['sort_by']);
 
 $a_v = array(
  'asc'=>'{Ascendant}',
  'desc'=>'{Descendant}',
 );
 
 $tpl_v['a_d'] = GetAdmSel($a_v, $clean['a_d']);
 $tpl_v['q'] = html_esc($clean['q']);
 
return $tpl->Parse(HW_MOD_TPL.'members.htm',$tpl_v);
 
 
}
 
if(!function_exists('GetAdmSel')){
 
function GetAdmSel($a_v,$s_cur = ''){
  $s = '';
  if($a_v) foreach($a_v as $k=>$v){
    $s.='<option'.($k==$s_cur?' selected':'').' value="'.$k.'">'.$v;
  }
  return $s;
}
 
}
 
?>

Open in new window

Avatar of alain34
alain34
Flag of United Kingdom of Great Britain and Northern Ireland image

Hello majdolyan,

Replace
$A_ITEMS = $db->two_col_assoc('SELECT userid,COUNT(*) FROM '.TBL_AD.' WHERE userid IN('.implode(',',$A_UID).') GROUP BY userid');
by
$A_ITEMS = $db->two_col_assoc('SELECT userid,COUNT(*) FROM '.TBL_AD.' WHERE userid IN('.implode(',',$A_UID).') GROUP BY userid irder by 2');

Regards,

alain34
majdolyan,

sorry
'irder' should be 'order'
$A_ITEMS = $db->two_col_assoc('SELECT userid,COUNT(*) FROM '.TBL_AD.' WHERE userid IN('.implode(',',$A_UID).') GROUP BY userid order by 2');

alain34
Avatar of majdolyan

ASKER

Thanks Alain but nothing has been changed in the display. Names are still not sorted by amount of ads.
I gave it more thought and I found your solution logically to be incorrect. The SQL statement you are ordering is inside the 2nd while loop which is responsible to count the amount of ads per user.

What I want is to order the users in the outer loop based on the number of their ads. But the problem in that SQL statement it's currently only for the users, I may need to join it with ad table to order users correctly from there.

But I don't know how!

Any help is appreciated.

Avatar of bleach77
bleach77

Check the #### mark
$ql = 'SELECT COUNT(*) FROM '.TBL_USER.' WHERE 1'; #### Delete this line
$ql = 'SELECT COUNT(*) FROM '.TBL_USER.' u LEFT JOIN (SELECT userid,COUNT(*) as amount FROM '.TBL_AD.' GROUP BY userid) a ON a.userid = u.id WHERE 1'; #### Use this line instead
 
 $sel_search_by = array(
   'username' => '{Username}',
 );
 
$add_url = '';
 
if($_GET['s_res']) {
  
  if($clean['search_by'] && $sel_search_by[$clean['search_by']] && $clean['q']) {
    $ql.=' AND '.$clean['search_by']." LIKE '%".addcslashes($db->quote($clean['q']), '%_')."%'";
  }
  if($clean['sort_by']) {
    $ql.=' ORDER BY "'.$clean['sort_by'].'" '.$clean['a_d'];
  }
  else {    ####  add this else
    $ql.=' ORDER BY a.amount'; 
  }
  $add_url='&s_res=1';
  if($clean['search_by'] && $clean['q']) $add_url.='&search_by='.$clean['search_by'].'&q='.urlencode($clean['q']);
  if($clean['sort_by']) $add_url.='&sort_by='.$clean['sort_by'].'&a_d='.$clean['a_d'];
}
else {    ####  add this else
    $ql.=' ORDER BY a.amount'; 
  }

Open in new window

Hi bleach77,

I got mySQL error code: 1064 near 'as amount FROM ec3_ad GROUP BY userid) a ON a.userid = u.id WHERE 1 ORDER BY a.a' at line 1

I'm using :

MySQL Version 5.0.67-community
PHP Version 5.2.3
Can you give the whole query.
Sorry, I miss the str_replace part
$ql = str_replace('COUNT(*)','id,username,UNIX_TIMESTAMP(regdate) AS regdate',$ql); #### Please include amount in 
$ql = str_replace('COUNT(*)','id,username,UNIX_TIMESTAMP(regdate), a.amount AS regdate',$ql); #### Use this

Open in new window

Ignore above post
$ql = str_replace('COUNT(*)','id,username,UNIX_TIMESTAMP(regdate) AS regdate',$ql); #### Please include amount in 
$ql = str_replace('COUNT(*)','u.id,u.username,UNIX_TIMESTAMP(u.regdate) AS regdate' a.amount,$ql); #### Use this

Open in new window

Please Ignore the other post. Sorry for any inconveniences.
$ql = str_replace('COUNT(*)','id,username,UNIX_TIMESTAMP(regdate) AS regdate',$ql); #### Please include amount in 
$ql = str_replace('COUNT(*)','u.id,u.username,UNIX_TIMESTAMP(u.regdate) AS regdate, a.amount',$ql); #### Use this

Open in new window

Hi, I have added the last change and I'm still getting the following error:


mySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'as amount FROM ec3_ad GROUP BY userid) a ON a.userid = u.id WHERE 1 ORDER BY a.a' at line 1
mySQL error code: 1064
Date: Friday 20th 2009f March 2009 02:04:22 PM
I still have the error code, any help is appreciated.
ASKER CERTIFIED SOLUTION
Avatar of bleach77
bleach77

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial