1

我一直在尝试根据分数获得用户的百分等级。我可以在 phpmyadmin 中获得结果 - 但似乎无法在 php 中获得正确的代码......

这是我到目前为止所拥有的......

$db=JFactory::getDBO();
$session =& JFactory::getSession();
$user =& JFactory::getUser();
$userId = $user->id;

$rank = "SELECT rank, cb_cscore,(SELECT 100*(rank / count(*)) FROM  `e72jm_comprofiler`,(SELECT @rownum :=0)r WHERE cb_cscore IS NOT NULL) as percentage FROM (SELECT @rownum := @rownum +1 AS rank, `cb_cscore` , `user_id` FROM `e72jm_comprofiler`,(SELECT @row :=0) r WHERE cb_cscore IS NOT NULL AND user_id = $userId LIMIT 0,1";

$db->setQuery( $rank );
$db->query();

但是 - 我一直卡在如何加载结果......

意思是如何从查询中加载结果.....

任何帮助将不胜感激...

4

3 回答 3

0

首先,您没有在查询中正确定义数据库表。您需要使用 prefix #__,因此在您的情况下,它将#__comprofiler代替e72jm_comprofiler

其次,您不需要使用&运算符,因此更改=& JFactory= JFactory

第三,删除$db->query();,因为它在将数据插入数据库或更新数据库时使用

然后你需要使用定义结果$rows = $db->loadObjectList();

最后,您可以使用foreach循环显示结果,因为它将是一个数组。

最终代码:

$db = JFactory::getDBO();
$session = JFactory::getSession();
$user = JFactory::getUser();
$userId = $user->id;

$rank = "SELECT rank, cb_cscore,(SELECT 100*(rank / count(*)) FROM  `#__comprofiler`,(SELECT @rownum :=0)r WHERE cb_cscore IS NOT NULL) as percentage FROM (SELECT @rownum := @rownum +1 AS rank, `cb_cscore` , `user_id` FROM `#__comprofiler`,(SELECT @row :=0) r WHERE cb_cscore IS NOT NULL AND user_id = $userId LIMIT 0,1";

$db->setQuery($rank);
$rows = $db->loadObjectList();

foreach ($rows as $row) {              
  echo $row->rank;
  echo $row->cb_cscore;
} 

我还建议您看看使用 Joomla 2.5 编码标准进行数据库查询:

http://docs.joomla.org/Selecting_data_using_JDatabase

希望这可以帮助

于 2013-09-19T02:34:27.873 回答
0

尝试这个,

$db=JFactory::getDBO();
$session =& JFactory::getSession();
$user =& JFactory::getUser();
$userId = $user->id;

    $rank = "SELECT rank, cb_cscore,
    (SELECT 100*(rank / count(*)) FROM  `e72jm_comprofiler`,
    (SELECT @rownum :=0)r WHERE cb_cscore IS NOT NULL) as percentage 
FROM (SELECT @rownum := @rownum +1 AS rank, `cb_cscore` , `user_id` FROM `e72jm_comprofiler`,

    (SELECT @row :=0) r WHERE cb_cscore IS NOT NULL) 
    AND user_id = $userId LIMIT 0,1";

$db->setQuery( $rank );
$db->query();
$res = $db->loadAssocList();//if the result is single row you can use $db->loadAssoc();
echo "<pre/>";
print_r($res);
于 2013-09-19T02:40:43.910 回答
0
$rank = "SELECT rank, cb_cscore,(SELECT 100*(rank / count(*)) as percentile FROM  `e72jm_comprofiler`,(SELECT @rownum :=0)r WHERE cb_cscore IS NOT NULL) as percentage FROM (SELECT @rownum := @rownum +1 AS rank, `cb_cscore` , `user_id` FROM `e72jm_comprofiler`,(SELECT @row :=0) r WHERE cb_cscore IS NOT NULL AND user_id = $userId LIMIT 0,1";

然后像其他任何一样访问它作为“百分位”列。

于 2013-09-19T02:12:36.697 回答