1

This is my line of code that shown products from database, but I want to show it randomly every time.

Code:

$products = DB::select("SELECT * FROM products ORDER BY category = 75 DESC LIMIT 4");
5
  • category = 75 looks like it should be in a where clause. Commented May 27, 2018 at 13:02
  • I'm, not programmer can you give me the full line of code?
    – gucci boss
    Commented May 27, 2018 at 13:03
  • There are many threads on this topic already, have you looked at them already and they didn't resolve the issue? Commented May 27, 2018 at 13:03
  • Are you wanting to select 4 random products with category 75?
    – Alessi 42
    Commented May 27, 2018 at 13:06
  • Based on your comments I don't think the question has a full description of what you want. Please update, the category = 75 is misleading, if you really want random categories. Commented May 27, 2018 at 13:09

2 Answers 2

1

Simply use RAND() to order randomly;

$products = DB::select("SELECT * FROM products where category = 75 ORDER BY RAND() LIMIT 4");
1
  • Thank you that is what i asked :)
    – gucci boss
    Commented May 27, 2018 at 13:11
1

Why you ordering by category = 75? You meant where category = 75?

You can use ORDER BY RAND():

$products = DB::select("SELECT * FROM products ORDER BY RAND() LIMIT 4");

but you may expect some performance issues.

5
  • Yeah, but i want to show random from a database category.
    – gucci boss
    Commented May 27, 2018 at 13:04
  • 75 is the category id.
    – gucci boss
    Commented May 27, 2018 at 13:04
  • @gucciboss Please define exactly what you want in the question. 4 random and different categories everytime? Commented May 27, 2018 at 13:07
  • So better way is select all categories from db, shuffle them in php and run your query with id from first row of shuffled array.
    – Daniel
    Commented May 27, 2018 at 13:07
  • Thank you, i have completed that.
    – gucci boss
    Commented May 27, 2018 at 13:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.