user1636946
user1636946

Reputation: 145

PHP SQL Joomla store table with two columns into array and echo them later

So I have a simple table with two columns. The table is called "mytable" and the columns are "product" and "id". The table has about 12 entries.

            $db = JFactory::getDbo();
            $query = "SELECT * FROM mytable";
            $db->setQuery($query);
            $results = $db->loadObjectList();

So I've gotten this far querying successfully but I want to call back the results of each row. That's the part I am stuck on. I need to store this into an array so I can later make a while loop spitting out each row. Also I cannot echo it right underneath that code. This needs to be stored in an array that is then pulled from another page and then I spit out each row. Thanks!

Upvotes: 1

Views: 466

Answers (2)

Jobin
Jobin

Reputation: 8272

Try this,

        $db = JFactory::getDbo();
        $query = "SELECT * FROM mytable";
        $db->setQuery($query);
        $results = $db->loadObjectList();
        echo '<pre/>'
        print_r($results);//the resulted array is already in this variable you can iterate it later with foreach loop.

for looping and printing

foreach($results as $key=>$value){
 echo 'Product-->'.$value->product;
 echo 'ID-->'.$value->id;
}

check the Joomla DB query for more details.

Hope it helps..

Upvotes: 1

Lodder
Lodder

Reputation: 19733

I would personally use more up to date coding standards for you query, like so:

$db = JFactory::getDbo();
$query->select($db->quoteName('*'))
      ->from($db->quoteName('mytable'));
$db->setQuery($query);
$results = $db->loadObjectList();

Then to get the results, create a loop:

foreach($results as $result) {
    echo 'ID = ' . $result->id;
    echo 'Product = ' . $result->product;
}

Hope this helps

Upvotes: 0

Related Questions