Reputation: 2104
I have this MySQL query :
while ($x <= 9) {
$data_1 = "SELECT scene FROM star WHERE star LIKE '%".$star."%' ORDER BY RAND() LIMIT 1";
$result_1 = mysql_query ($data_1) OR die("Error: $data_1 </br>".mysql_error());
while($row_1 = mysql_fetch_object($result_1)) {
$scene = $row_1->scene;
$x = $x + 1;
}
}
I want to get everytime a new scene for each execution, but I always get the same scene. Whats the issue? Can someone make me a few pointers in which direction I have to search ?
Upvotes: 0
Views: 1706
Reputation: 21230
What you need to do is tie a random seed to each row, and tie a new one each time. Do this by assigning a random value as an aliased transient column to your table, and then select from it.
SELECT s.scene as scene FROM (
SELECT stars.scene as scene, RAND() as seed
FROM stars
WHERE star LIKE '%".$star."%'
ORDER BY seed
) s
LIMIT 1;
Using PDO it's going to look something like this:
function getScene() {
$sql = 'SELECT s.scene as scene FROM ( SELECT stars.scene as scene, RAND() as seed FROM stars WHERE star LIKE '%:star%' ORDER BY seed ) s LIMIT 1;';
$query = $this->db->prepare($sql);//'db' is the PDO connection
$query->execute(array(':star' => "Allison Brie"));
foreach ($conn->query($sql) as $row) {
print $row['scene'] . "\t";
}
}
I'm not sure what you were trying to accomplish with the rest of your code, but it mostly looks like cruft.
Upvotes: 4