简体   繁体   中英

Display MySQL select query results in Joomla framework

I'm trying to fetch query results from Joomla MySQL database in a Joomla page. The print_r is returning proper results which the db connection is proper. But I'm not able to display the data that has been fetched. Here's the result that I'm getting at the moment for print_r:

mysqli_result Object ( 
    [current_field] => 0 
    [field_count] => 2 
    [lengths] => [num_rows] => 2 [type] => 0 
) 

Here's the code that I'm using:

{source}
<script language="javascript" type="text/javascript">

</script>
<?php


    // init Joomla Framework
    define( '_JEXEC', 1 );
    define( 'DS', DIRECTORY_SEPARATOR );
    define( 'JPATH_BASE', realpath(dirname(__FILE__).DS.'..' ));


    require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
    require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );

    $mainframe = JFactory::getApplication('site');

    // DBQuery
    $database =& JFactory::getDBO();
    $query = "SELECT city_id, city_name FROM indytoad_city;";
    $database->setQuery($query);
    $result = $database->query();

    print_r($result);
?>
{/source}

Please let me know how and where and what I need to amend in order to display the query results.

Use loadAssocList() instead of query() , ie

$result = $database->loadAssocList();

It gets the data from the database as an associative array.

Joomla documentation: http://docs.joomla.org/JDatabase::loadAssocList/11.1

I dont want to go into details of convention used in Joomla to retrive result from database. This entirely depends on the developer.

The reason you dont get the value because you probably treat the result array as an associative array. It is actually an stdClass object !

use

$result->city_id

to get the values of city_id, if in case of multiple nested classes are there, you can use it as

$result->parent->child

Hope this helps !

for more info you can check this one out -> https://stackoverflow.com/a/931419/122840

Also instead of

$result = $database->query();

use :

$result = $database->loadAssocList();

This loads the result in Associated array!

so you use

$result['column']

to get the result !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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