Question

Ok, so I am trying to get a list of images to display randomly, rather than the first 6 or the last 6. Both works fine if showing it in ASC or DESC, however, as soon as I add RAND, nothing shows anymore, it just thinks there are no images and shows 'No images'. I've tried moving the RAND about and also tried replacing DESC etc with RAND, but the whole website either loads blank or it just thinks there is no content to show.. anyone able to shed some light on where I'm going wrong??

Here is the code in question, let me know if you want to see more of the code..

/**
  * Return manufacturers
  *
  * @param boolean $get_nb_products [optional] return products numbers for each
  * @return array Manufacturers
  */
public static function getManufacturers($get_nb_products = false, $id_lang = 0,    
    $active = true, $p = false,
    $n = false, $all_group = false)
{
    if (!$id_lang)
        $id_lang = (int)Configuration::get('PS_LANG_DEFAULT');

    $sql = 'SELECT m.*, ml.`description`, ml.`short_description`
        FROM `'._DB_PREFIX_.'manufacturer` m
        LEFT JOIN `'._DB_PREFIX_.'manufacturer_lang` ml ON (
            m.`id_manufacturer` = ml.`id_manufacturer`
            AND ml.`id_lang` = '.(int)$id_lang.'
        )
        '.Shop::addSqlAssociation('manufacturer', 'm');
        if ($active)
            $sql .= '
        WHERE m.`active` = 1';
        $sql .= '
        GROUP BY m.id_manufacturer
        ORDER BY m.`name` DESC'. 

        ($p ? ' LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n : '');

I have been changing the following code;

ORDER BY m.`name` DESC'. 

To one of the following, none of which have worked;

ORDER BY m.`name` RAND'. 
ORDER BY RAND m.`name` DESC'. 
ORDER BY m.`name` RAND() 
Was it helpful?

Solution

From the MySQL reference manual:

You cannot use a column with RAND() values in an ORDER BY clause, because ORDER BY would evaluate the column multiple times.

Eg: you can use ORDER BY RAND(), but not ORDER BY column RAND() as the above example shows

Edit: Expanded based on comments below to include emphasis and example.

OTHER TIPS

You should use

ORDER BY RAND()

or

ORDER BY m.`name` DESC, RAND()

Ok, I figured it out. Thanks everyone for pointing me in the right direction.

Basically I removed this code;

    $sql .= '
    GROUP BY m.id_manufacturer
    ORDER BY m.`name` DESC'. 

and replaced it with;

    $sql.= ' ORDER BY RAND()'.

Most likely, your problem is in this line of code and similar ones:

   FROM `'._DB_PREFIX_.'manufacturer` m

You are escaping with backticks the entire expression. Something like:

FROM `db.manufacturer`

That refers to a table called db.manufacturer in the current database. Not the table manufacturer in the database db.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top