Вопрос

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).

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.

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();
Это было полезно?

Решение

You should stick to Joomla coding standards for your query like so:

$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:

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

Другие советы

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.

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

Side note, INT values don't need encapsulation.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top