Array with Mysql

0

I'm trying to make a music draw 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 />";
    
asked by anonymous 26.04.2016 / 18:57

1 answer

0

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

SELECT nome FROM CadMusicas ORDER BY RAND()

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

If it's just a registration, do this:

$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 badly on large banks   of data, I think that is not your case, but one solution is to use this:

SELECT nome FROM CadMusicas WHERE RAND()<(SELECT ((1/COUNT(*))*10) FROM CadMusicas) ORDER BY RAND() LIMIT 1
    
26.04.2016 / 19:23