Weird Rand() Thing

mairving's picture

They have: 2,256 posts

Joined: Feb 2001

This SQL statement works in MySQL to return a random quote.

<?php
SELECT
* from tablename ORDER BY RAND() LIMIT 1;
?>

Basically it returns a quick and dirty random value from the database.
It also works in PHP on my local machine using PHP 4.1.2. On my host's machine running PHP 4.2.2, it doesn't work. It produces the same value every time. I have trying freeing the results and closing the connection, but so far no joy.

Any ideas?

Mark Irving
I have a mind like a steel trap; it is rusty and illegal in 47 states

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

Very odd. What version of mySQL do the two machines have?
(I'm doubting PHP has anything to do with it)

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

just checked, you need mySQL version 3.23 to do "ORDER BY RAND()"

I can't find anywhere that mentions problems with later versions.

mairving's picture

They have: 2,256 posts

Joined: Feb 2001

MySQL is 3.23.39. It can't be MySQL because when I log in via SSH and run the query in MySQL, it works fine.

He has: 1,016 posts

Joined: May 2002

PHP's rand() changed since PHP 4.2.0, now you don't need to seed it anymore and the syntax is rand( [min value, max value )

So to get a random number between 1 and 10 you would do rand(1, 10);

mairving's picture

They have: 2,256 posts

Joined: Feb 2001

Quote: Originally posted by zollet
PHP's rand() changed since PHP 4.2.0, now you don't need to seed it anymore and the syntax is [b]rand( [min value, max value )

So to get a random number between 1 and 10 you would do rand(1, 10); [/B]

Yes, I have seen that the rand function doesn't have to be seeded any more. The thing is that this really shouldn't have anything to do with PHP. It should have to do with MySQL since I am pulling the random field out with a Select statement.

Mark Irving
I have a mind like a steel trap; it is rusty and illegal in 47 states

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

Like Mark Irving, I'm thinking that because the RAND() is in the SQL statement, PHP shouldn't touch it.

What kind of quotes is your SQL statement in?

Mark Hensler
If there is no answer on Google, then there is no question.

mairving's picture

They have: 2,256 posts

Joined: Feb 2001

Here is the query, nothing different.

<?php
$result
=mysql_query(\"SELECT guestbook_message, guestbook_name from guestbook order
by RAND() limit 1\");
$row = mysql_fetch_array($result);
?>

Mark Irving
I have a mind like a steel trap; it is rusty and illegal in 47 states

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.