3

I have been asked to get related stuff to what the user has in his items

so as far as the database was created this items table stores the category name so, i thought to get the category name and save it into an array

and then do a for loop and get one random value from it

and after that get a random row from mysql database so anyone has an idea how to do this

in other words i want to know how to get a random value from an array and a random row from mysql

Thanks in advance.

3 Answers 3

3

use

 $rand_keys = array_rand($input, 1);

see example http://php.net/manual/en/function.array-rand.php for php and for mysql

 SELECT * FROM tbl_name ORDER BY RAND() LIMIT 1

use this

Sign up to request clarification or add additional context in comments.

8 Comments

to select a random row from an array, you should ORDER BY RAND() LIMIT 1
@sujal Thanks a lot for your reply i will try this and inform you about the result
@Not_a_Golfer Thanks a lot for informing me about the LIMIT 1 part you have saved the day
@MohamedHassan I am waiting for your answer
can i ask about what it does return a row or number?
|
2

To get a random element from an array in PHP you can use array_rand.

To get a random row from a MySQL query you can use RAND() so something like

ORDER BY RAND() LIMIT 1

But note that this method in MySQL can have performance implications.

2 Comments

what implications you mean?? and do you think there is a better approach?
@MohamedHassan Performance can degrade if your table gets big: titov.net/2005/09/21/… On small tables it's not a worry but if there's any chance your table might grow then you might want to think about an alternative from the outset.
0

quote from http://php.net/manual/de/function.rand.php:

ilya dot iz at i dot ua 27-Jul-2011 08:09 I had to come up with a quick way to get a random row from a table, and came up with the following: ...

Should be easy to get a random value from an array with something like rand(0,count(arrayvar))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.