多个MySQL输入


Multiple MySQL Inputs

我有一个脚本,看起来像这样,它检索人们在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用户正在听的所有歌曲,然后将它们存储在他们的当前歌曲字段中。

我试着在顶部添加以下内容:

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

然后将以下内容放到底部:

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

但是失败了,所以我不知道该怎么做。如有任何帮助,我们将不胜感激。

$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);
}