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() 提供的参数无效”。谁能帮我找歌?提前致谢。

4

3 回答 3

0

应该是这样的:

$favsr = mysql_fetch_array($getfavq, MYSQL_ASSOC);
foreach($favsr as $row) {
    $songid = $row['bookmarked_song_id'];
     ...
}
于 2012-05-22T18:29:27.860 回答
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'];}
于 2012-05-22T18:33:18.720 回答
0

您已将此标记为codeigniter。如果您正在构建 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
}

当然,最好的做法是将您的用户数据和收藏夹数据放在不同的模型中,但这目前应该可行。

于 2012-05-22T20:21:48.370 回答