2013-08-01 66 views
0

我有一個腳本,它看起來像這裏面獲取歌曲信息,人們在LastFM等歌曲記錄:多個MySQL輸入

class NowPlaying{ 

    private $url; 
    private $noTrackPlayingMessage; 

    function __construct($user, $api_key){ 

     // construct URL 
     $this->url = 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&limit=1'; 
     $this->url .= '&user=' . $user . '&api_key=' . $api_key; 

     // default message 
     $this->noTrackPlayingMessage = 'Nothing is playing right now!'; 
    } 

    // return the artist and track currently playing 
    public function getNowPlaying(){ 

     // create an XML object 
     $xml = simplexml_load_file($this->url); 

     // get the latest track 
     $track = $xml->recenttracks->track; 

     // check if the track is actually playing 
     $nowplaying = $track->attributes()->nowplaying; 

     // return the track and artist if music is playing, otherwise show message 
     if($nowplaying){ 
      $artist = $track->artist; 
      $songname = $track->name; 
      return $artist . ' - ' . $songname; 
     } 
     else{ 
      return $this->noTrackPlayingMessage; 
     } 
    } 

    // set the message to be shown when no music is playing 
    public function setNoTrackPlayingMessage($messageIn){ 
     $this->noTrackPlayingMessage = $messageIn; 
    } 

} // end class 

$nowPlaying = new NowPlaying($id, 'APIGOESHERE'); 
$nowPlaying->setNoTrackPlayingMessage($id); // optional 
$currentplaying = $nowPlaying->getNowPlaying(); 

雖然這只是個別LastFM等帳戶有用的,但是我想運行通過幾個賬戶這個腳本中的細節存儲在一個MySQL數據庫中。我的表有兩列,lastfmusername和presentong。我想要找到那些lastfm用戶正在收聽的所有歌曲,然後將它們存儲在他們當前的字段中。

我試着加入以下頂端:

$sql = "SELECT lastfmusername FROM data"; 
$id = $db->query($sql); 

然後將下面的底部:

$sql2 = "UPDATE lastfmtable SET currentsong = '$currentplaying' WHERE lastfmusername = '$id'"; 
$cursong = $db->query($sql2); 

但失敗,所以我不知道如何處理這一點。任何幫助,將不勝感激。

回答

0
$sql = "SELECT lastfmusername FROM data"; 

將返回一個數組,其中包含lastfmusername的所有值,而不僅僅是一個。

試試這個:

$sql = "SELECT lastfmusername FROM data"; 
$users = $db->query($sql); 
$id = $users[0]['lastfmusername']; 

意思是:$ id將現在存儲的第一個結果。

您需要遍歷用戶的結果併爲每個用戶運行更新查詢。所以,你正在嘗試做的應該是這樣的:

foreach($users as $r){ 
    $id= $r['lastfmusername']; 
    $nowPlaying = new NowPlaying($id, 'APIGOESHERE'); 
    $nowPlaying->setNoTrackPlayingMessage($id); // optional 
    $currentplaying = $nowPlaying->getNowPlaying(); 
    $sql2 = "UPDATE lastfmtable SET currentsong = '$currentplaying' WHERE lastfmusername = '$id'"; 
    $cursong = $db->query($sql2); 
} 
+0

謝謝,我只是嘗試過,但我得到了錯誤「致命錯誤:調用一個成員函數屬性()在file.php一個非對象在第27行「,第27行包含」$ nowplaying = $ track-> attributes() - > nowplaying;「 – Christian

+0

該錯誤與您的lastfm類有關,並且是由您以錯誤格式(字符串,數組,整數或對象)發送參數引起的。顯然,你的班級想要一個對象。很難說像這樣。把所有相關的代碼放在jsfiddle.net上併發布回鏈接。另外,請提供您的my​​sql Select查詢返回的示例行。 – pixeline