Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have this function:

function set_spell() {
global $connection;
$query = "SELECT * FROM Spells";
$result_set = mysqli_query($connection, $query);
$spell_id_list = mysqli_fetch_array($result_set);
return $spell_id_list;

Then I try to output a random ID from the array, but I always get ID 1.

$spell_id_list = set_spell();
echo $spell_id_list[array_rand($spell_id_list)];

When I run this query in MYSQL, I get a list of all ID's as expected. Why doesn't the code above select one at random?

This is probably a stupid questions that I'll smack myself after I see the answer... but I've been stuck for longer than I think I should be on it.

Thanks for the help.

share|improve this question
 
What you want to achieve ? Array of random result or just one random value ? –  Rikesh May 12 '13 at 4:57
 
Don't use global, instead pass the connection as a param –  Mr. Alien May 12 '13 at 4:59
 
It's been a while, but doesn't *_fetch_row just get one result? So doesn't $spell_id_list only have on item when set_spell is returned? –  BrianDHall May 12 '13 at 4:59
 
Trying to grab a single random ID from the array. @Mr. Alien how do I do that instead of using global? Yes, typo on the fetch_row, i tested w/ fetch_array and same problem. –  Jeff Solomon May 12 '13 at 5:58
add comment

1 Answer

You just returning only single result from your function so either create array of all fetched results & return the same, or simply use order by rand() in your query,

SELECT * FROM Spells ORDER BY RAND();
share|improve this answer
 
Yeh, originally did w/ ORDER BY RAND() in the MYSQL statement but heard that wasn't totally random or good practice. How do I create the array with ALL fetched results vs. one? As I said in the comment above, I used msqli_fetch_array and still get the same? –  Jeff Solomon May 12 '13 at 5:59
 
Just loop over mysqli_fetch_array & built a resultant array. –  Rikesh May 12 '13 at 7:37
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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