2

I am trying to practice programming and I have decide to place some effect on the login page. Since I am working on an online store I would want to display some random products somewhere in the login page that changes after every few seconds.

Now, I am stuck on how will I be able to extract a single product that will be displayed after an ajax call. I was thinking of getting the minimum and maximum product id on the database then randomly generate a number between the minimum and maximum product id then get the product with that ID but I thought that what if the ID that is randomly generated doesn't match any product. It will just display nothing on the login page for seconds which I don't want to happen.

Is there a way that I can have an ID that will surely be in the product table? Your help will be greatly appreciated. Thanks in advance.

PS:

I am using MySQL and PHP.

UPDATE:

I have came across a page stating that I can use:

SELECT * FROM `table` ORDER BY RAND() LIMIT 0,1;

Will this be a good solution for it?

Atasha
  • 489
  • 1
  • 9
  • 28

1 Answers1

4

If you are using MSSql you can order by the newId() function to randomly get a row of data. You still need a service/page on the server side to run this code for you.

select top 1 productName, sku
from products
order by newid()

for MySql this would suffice

SELECT productName, sku
FROM products
ORDER BY Rand()
LIMIT 1
Matt
  • 3,638
  • 2
  • 26
  • 33