Avoid document.write
. By putting each Song Object inside of your Array you can achieve this:
var myArray = [{title:'Song 1 Title', artist:'Song 1 Artist'}, {title:'Song 2 Title', artist:'Song 2 Artist'}, {title:'Song 3 Title', artist:'Song 3 Artist'}];
function getRandomSong(ary){
return ary[Math.floor(Math.random()*ary.length)];
}
var randomSong = getRandomSong(myArray);
console.log(randomSong.title); console.log(randomSong.artist);
Of course, if you have thousands of songs you'll want to execute something similar Sever Side on your database. In PHP this might look like:
<?php
class Song{
private $db; public $currentSelection;
public function __construct($databaseConnection){
$this->db = $databaseConnection;
$this->currentSelection = $this->getRandomSong();
}
public function getRandomSong(){
$db = $this->db;
if($sq = $db->query('SELECT COUNT(*) count FROM songTable')){
if($sq->num_rows > 0){
$c = $sq->fetch_object(); $rc = rand(1, $c->count);
if($rq = $db->query("SELECT * FROM songTable WHERE primaryKey=$rc"){
if($rq->num_rows > 0){
return json_encode($rq->fetch_assoc());
}
else{
// no rows
}
$rq->free();
}
else{
// connection failure
}
}
else{
// no rows
}
$sq->free();
}
else{
// connection failure
}
return false;
}
}
$songObj = new Song($databaseConnectionHere);
echo $songObj->currentSelection;
echo $songObj->getRandomSong();
$dataBaseConnectionHere->close();
?>