简体   繁体   English

Joomla 2.5中的查询数据库

[英]Query database in Joomla 2.5

I'm using Joomla 2.5 and I need to retrieve the field 'avatar' for the current user. 我正在使用Joomla 2.5,我需要为当前用户检索字段“头像”。

This is the code I'm using: 这是我正在使用的代码:

$user = JFactory::getUser();
$id = $user->get('id');

$db = JFactory::getDbo();
$query = $db->getQuery(true);

$query->select('avatar')
 ->from('#__discuss_users')
 ->where('id = $id');

$db->setQuery($query);
$results = $db->loadObjectList();

But it isn't displaying any data. 但是它不显示任何数据。 I tried changing the last line to: 我尝试将最后一行更改为:

$results = $db->loadResult();

But it doesn't work either. 但这也不起作用。

If you are using it as you posted, you won't include the actual value of $id in your query. 如果您在发布时使用它,则不会在查询中包含$ id的实际值。 You need to append it to the string like this: 您需要将其附加到这样的字符串中:

$query->select('avatar')
 ->from('#__discuss_users')
 ->where('id = '.$id);

I am usually not using the $query->select stuff, but a plain old query. 我通常不使用$ query-> select东西,而是一个普通的旧查询。 Thus, you might try to do it like this (this might not be best practice though): 因此,您可以尝试这样做(尽管这可能不是最佳实践):

$user = JFactory::getUser();
$id = $user->get('id');

$db = JFactory::getDBO();  
// $query = $db->getQuery(true);

$query = "SELECT ".$db->quoteName('avatar')
         ." FROM ".$db->quoteName('#__discuss_users')
         ." WHERE ".$db->quoteName('id')
         ." = ".$db->quote($id).";";

// $query->select('avatar')
// ->from('#__discuss_users')
// ->where('id = $id');

$db->setQuery($query);
$results = $db->loadObjectList();

Thanks for your help. 谢谢你的帮助。 The following code works: 以下代码有效:

$user = JFactory::getUser();
$id = $user->get('id');

$db = JFactory::getDbo();
$query = $db->getQuery(true);

$query
 ->select($db->quoteName('avatar'))
 ->from($db->quoteName('#__discuss_users'))
 ->where('id = '.$id);

$db->setQuery($query);
$results = $db->loadResult();
echo $results;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM