MySQL Query to show images

by RustyJoomla   Last Updated May 10, 2017 11:10 AM

I want to show up to 3 images that are assigned to the logged in user in a database table. I have written the following MySQL query:

    $db = JFactory::getDBO();
    //GET GALLEERY IMAGES
    $query = $db->getQuery(true);
    $query->select('*');
    $query->from('#__mcloud_mgallery');
    $query->where('model_id = '.$userid);
    $query->order('id');
    $db->setQuery($query);
    $rows = $db->loadObject();

    $gallery_img = $rows->file;

If I echo $gallery_img this outputs only one of the images, if I look in the database table (for the logged in user) there are 3 images assigned to that user:

id      file                    model_id

389     10_burgers_food.jpeg    941
390     14_bridge.jpeg          941
391     test_imag.jpeg          941

How can I show the 3 images if there's only 1 variable '$gallery_img' ?

Tags : php mysql


Answers 1


Problem being is you're using loadObject() which will only ever return 1 result. If you want multiple, you'll need to use loadObjectList(), like so:

$db = JFactory::getDbo();

$query = $db->getQuery(true);
$query->select('*')
      ->from($db->qn('#__mcloud_mgallery'))
      ->where($db->qn('model_id') . ' = ' . $userid)
      ->order('id');
$db->setQuery($query);

$rows = $db->loadObjectList();

foreach ($rows as $row)
{
    echo '<p>' . $row->file . '</p>';
}

Just incase there will ever be more than 3 images in the database, you can also limit the results in the query to 3, like so:

$query->select('*')
      ->from($db->qn('#__mcloud_mgallery'))
      ->where($db->qn('model_id') . ' = ' . $userid)
      ->order('id')
      ->setLimit('3'); // <-- Here
$db->setQuery($query);

Hope this helps

Lodder
Lodder
May 10, 2017 10:49 AM

Related Questions


What's the proper chaining for WHERE

Updated January 29, 2018 18:10 PM

Display a Value from a Specific DB Field

Updated April 30, 2016 08:04 AM


Delete users from Joomla V2.5

Updated November 08, 2016 08:04 AM