0

我有一个看起来像这样的脚本,它可以检索人们在 LastFM 上搜索的歌曲信息:

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 和 currentsong。我想找到所有 lastfm 用户正在听的歌曲,然后将它们存储在他们的 currentsong 字段中。

我尝试将以下内容添加到顶部:

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

然后到底部:

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

但这失败了,所以我不确定如何解决这个问题。任何帮助,将不胜感激。

4

1 回答 1

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);
}
于 2013-08-01T01:28:30.153 回答