Page 1 of 1

RE: Generating a Random Number through database COUNT

Posted: Wed Jan 21, 2004 11:38 am
by TheWaterboy08
Im trying to generate a random number between 1 and the number of rows in my table. This random number will then be used to query the same table. The idea is that a new row from the table will be displayed each time the page is viewed or reloaded. Here is the code. Unfortuntly i seem to be getting 0 each time thoug the count is 10. Can anyone tell me what im doing wrong. :?

$query= mysql_query("select count(*) from gossip where published is not null order by published desc");
$visitcount = mysql_result($query,0);

//generate random number
srand((double)microtime()*1000000);
$number = rand(0,$vistcount);

//use random number to query table
$story_sql=mysql_query("select * from gossip where published is not null and gossip_id ='".$number."' order by published desc");

Posted: Wed Jan 21, 2004 11:49 am
by redmonkey

Code: Select all

select * from gossip where published is not null order by rand() limit 1

Posted: Wed Jan 21, 2004 1:36 pm
by phpcoder
$visitcount = mysql_result($query,0);
may b u r not getting any values in $visitcount

Posted: Wed Jan 21, 2004 2:02 pm
by TheWaterboy08
Yes i dont think that im getting a value in $vistcount as when i echo $vistcount nothing is produces. Why is this because it should return a value of 10 ad there are 10 records in the table

Posted: Wed Jan 21, 2004 2:32 pm
by pickle
I've never used mysql_result - I always get the first row, then get element from that. Like so:

$results = mysql_query("select count(*) as 'count' from gossip......");
$row = mysql_fetch_assoc($results); <-- will return first row of results as an array, indexed by field names

$row_count = $row[count];

This may not be the tidiest way of getting the data, but if you print_r($row), you can see everything that the query retrieved. Quite helpful when debugging.

Posted: Wed Jan 21, 2004 2:35 pm
by phpcoder
If u want only number of rows in ur table then do this

Code: Select all

$query= mysql_query("select * from gossip where published is not null order by published desc"); 
$rows=mysql_num_rows($query);