RE: Generating a Random Number through database COUNT

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
TheWaterboy08
Forum Newbie
Posts: 4
Joined: Wed Oct 15, 2003 10:12 am

RE: Generating a Random Number through database COUNT

Post 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");
redmonkey
Forum Regular
Posts: 836
Joined: Thu Dec 18, 2003 3:58 pm

Post by redmonkey »

Code: Select all

select * from gossip where published is not null order by rand() limit 1
User avatar
phpcoder
Forum Contributor
Posts: 158
Joined: Sat Nov 02, 2002 1:18 pm
Location: Manchester, UK

Post by phpcoder »

$visitcount = mysql_result($query,0);
may b u r not getting any values in $visitcount
TheWaterboy08
Forum Newbie
Posts: 4
Joined: Wed Oct 15, 2003 10:12 am

Post 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
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
phpcoder
Forum Contributor
Posts: 158
Joined: Sat Nov 02, 2002 1:18 pm
Location: Manchester, UK

Post 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);
Post Reply