Reputation: 43
I am making a random post generator and the code looks like this:
<?php
$idea_generator = array();
$ideas_sql = "SELECT * FROM Ideas";
$query = mysql_query($ideas_sql);
while($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
$keywords = $row['keywords'];
//Need to add a link function
array_push($idea_generator, $name);
sort($idea_generator);
$number = count($idea_generator);
//randomly selects idea
$winner = $idea_generator[rand(0, $number -1)];
print strtolower($winner);
}
?>
My problem is that this code returns 3 items out of the test database in different orders. This project is designed to take out only 1 item from this database. Should I stick with this php array method or is there an easier way to accomplish this goal.
Upvotes: 0
Views: 704
Reputation: 6732
Change your query to this to retrieve one row at random:
$ideas_sql = "SELECT * FROM Ideas ORDER BY RAND() LIMIT 1;";
As this query only returns one row, you no longer need to select one random row in your PHP code. Your final code could be like this:
$ideas_sql = "SELECT * FROM Ideas ORDER BY RAND() LIMIT 1;";
$query = mysql_query($ideas_sql);
$row = mysql_fetch_assoc($query);
// This is your 'winning' row
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
$keywords = $row['keywords'];
Upvotes: 3