2012-05-22 81 views
0

我有一個名爲「收藏夾」的數據庫中有3列(user_id,bookmarked_song_id,bookmark_tag),我想獲取當前用戶的所有Bookmarked_song_id。獲取當前用戶的所有收藏夾

$username = $this->session->userdata('username'); 
$uidq = mysql_query('SELECT user_id FROM users WHERE username="' . $username . '"'); 
$rq = mysql_fetch_assoc($uidq); 
$user_id = $rq['user_id']; 
$getfavq = mysql_query("SELECT * FROM favorites WHERE user_id=$user_id"); 
$favsr = mysql_fetch_array($getfavq); //contains all the information from the favorites database where user_id is the user_of the currently logged-in user 

而且我不知道接下來要使用什麼......我想有這樣的:

foreach($favsr['bookmarked_song_id'] as $song_id) { 
$getsongq = mysql_query("SELECT * FROM songs WHERE song_id=$song_id"); 
$getsongr = mysql_fetch_assoc($getsongq); 
$singer = $getsongr['singer']; 
$song_name = $getsongr['song_name'];} 

顯然的方法是錯誤的,因爲我得到:「爲的foreach提供了無效的參數( )」。任何人都可以幫我獲取歌曲嗎?提前致謝。

回答

0

它應該是這樣的:

$favsr = mysql_fetch_array($getfavq, MYSQL_ASSOC); 
foreach($favsr as $row) { 
    $songid = $row['bookmarked_song_id']; 
    ... 
} 
0

mysql_fetch_array只會加載一行, 它應該是這樣的

$getfavq = mysql_query("SELECT * FROM favorites WHERE user_id=$user_id"); 
while $favsr = mysql_fetch_array($getfavq); 
    {$songid=$favsr['bookmarked_song_id']; 
    $getsongq = mysql_query("SELECT * FROM songs WHERE song_id=$song_id"); 
    $getsongr = mysql_fetch_array($getsongq); 
    $singer = $getsongr['singer']; 
    $song_name = $getsongr['song_name'];} 
0

你有這個標記codeigniter。如果你建立一個笨的應用程序,你應該使用CI的數據庫庫:

$username = $this->session->userdata('username'); 

//Select your user 
$this->db->select('user_id'); 
$this->db->where('username', $username); 
$this->db->limit(1); 
$user_query = $this->db->get('users'); 

if($user_query->num_rows() > 0) 
{ 
    // We found a user 
    $user = $user_query->row(); // select a single row 

    // Grab this user's favorites 
    $this->db->where('user_id', $user->id); 
    $favorites_query = $this->db->get('favorites'); 

    $songs = $favorites_query->result(); 

    if($songs) 
    { 
     foreach($songs as $song) 
     { 
      $song_id = $song->bookmarked_song_id; 
      $tag = $song->bookmark_tag; 

      // Do stuff with data. 
     } 
    } 
    else 
    { 
     // No songs/favorites found, catch error 
    } 

} 
else 
{ 
    // No such user found, catch error 
} 

當然,最好的做法是讓你的用戶數據,並在不同的模型您的收藏夾數據,但這應該對現在的工作。

+1

是的,我使用Codeigniter,因此您的答案完全符合我的項目。我只是寫了主要想法,之後我可能會將其轉換爲Codeigniter風格的代碼。 – dpanayotov

+0

優秀。祝你好運! – Seabass