Array with Mysql

Asked

Viewed 70 times

0

I’m trying to make a draw of songs but it always displays the last song registered in the database

$sql = "SELECT nome FROM CadMusicas"; 
$result = mysql_query($sql, $conecta); 


while($consulta = mysql_fetch_array($result)) { 
   $antigos= array($consulta[nome]);
   $numMusicas= sizeof($antigos);
   # Primeiro ganhador
   $sorteado[1] = $antigos[rand(0,$numMusicas- 1)];
} 


echo "<b>Musicas Sorteadas:</b> <br />";
echo "<b>1°</b> - " . $sorteado[1] . "<br />";
  • 1

    "... always displays the last song registered in the database" ... and what is your doubt? what’s the problem? what do you want help?

1 answer

0

I believe the best thing to do is to use the RAND.

SELECT nome FROM CadMusicas ORDER BY RAND()

This will return the records in a random order, it will depend on how your database is structured, each song must be a 'line'!

If it’s just a record, do it:

$sql = 'SELECT nome FROM CadMusicas ORDER BY RAND() LIMIT 1';

$result = mysql_query($sql, $conecta); 

$consulta = mysql_fetch_array($result);
echo $consulta['nome'];

Note: RAND performs terribly poorly in large banks but one solution is to use this:

SELECT nome FROM CadMusicas WHERE RAND()<(SELECT ((1/COUNT(*))*10) FROM CadMusicas) ORDER BY RAND() LIMIT 1
  • worked out just that I need this to be repeated 3x and there are times that it repeats and it can’t! how would this look?

  • I tried to use distinct but it didn’t help "SELECT distinct name FROM Cadmusicas ORDER BY RAND() LIMIT 1"

  • distinct only serves in the query. Mysql does not save what was generated unless you save the generated value to a table yourself, so use NOT IN. You have two alternatives besides creating such a table. Use LIMIT 3, this will have 3 results, use nome NOT IN(), see the Mysql manual at http://dev.mysql.com/doc/refman/5.7/en/any-in-some-subqueries.html. This way you store in Session or variable the previous name and it wouldn’t be selecting it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.