简体   繁体   English

Joomla Jdatabase访问不起作用

[英]Joomla Jdatabase access does not work

I just started to learn about joomla (3.x) and installed a part of the example component with a view and model (reference http://docs.joomla.org/J3.3:Developing_a_MVC_Component/Adding_a_model_to_the_site_part ). 我刚刚开始学习joomla(3.x),并安装了带有视图和模型的示例组件的一部分(请参考http://docs.joomla.org/J3.3:Developing_a_MVC_Component/Adding_a_model_to_the_site_part )。

When I added some database code to the model -see below- I got the error message: 当我向模型添加一些数据库代码时(请参阅下文),我收到了错误消息:

The requested page cannot be found.

An error has occurred while processing your request.

#0  SQL=SELECT username FROM '#__users' WHERE id='391'

I assume my query is wrong (I deliberately used the string instead the object for the query), but I don't understand what is wrong with it? 我以为我的查​​询是错误的(我故意使用字符串代替查询的对象),但是我不明白这是怎么回事? (ps: I checked that the table with __users as well as the tablefields id and username exist. (ps:我检查了具有__users以及tablefields id和username的表是否存在。

the related code (of model part): 相关代码(模型部分):

                    // Get a db connection.
                    $db = JFactory::getDbo();

                    // Create a new query 
                    //$query = $db->getQuery(true); //Option A: Create a new query object
                    $query = "SELECT username FROM '#__users' WHERE id='391' "; //Option B (classic method): SQL query string
                    $db->setQuery($query);

                    //Execute query
                    $db->execute();

                    //Get single DB result
                    //if($result)
                     $this->msg = 'Hello '.$db->loadResult();

The issue is your quoting the table name, when backticks (at most) should be used. 问题是您应引用表名,而最多应使用反引号。 Backticks really only need to be used in the event that your table name shares with a reserved mysql name. 实际上,仅在表名与保留的mysql名称共享的情况下才需要使用反引号。

"SELECT username FROM `#__users` WHERE id=391 "

Side note, INT values don't need encapsulation. 旁注,INT值不需要封装。

You should stick to Joomla coding standards for your query like so: 您应遵循Joomla编码标准进行查询,如下所示:

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

$query->select($db->quoteName('username'))
      ->from($db->quoteName('#__users'))
      ->where($db->quoteName('id') . ' = ' . (int) 391));

$db->setQuery($query);    
$result = $db->loadResult();

But if you are trying to get the username of s user with a specific ID, then you can simply use the following: 但是,如果您尝试获取具有特定ID的s用户的用户名,则可以使用以下命令:

$user = JFactory::getUser(391);
$this->msg = 'Hello '. $user->get('username');

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

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