Question

I've got a table in the database called "favorites" with 3 columns (user_id, bookmarked_song_id, bookmark_tag) and I want to get all the Bookmarked_song_id for the current user.

 $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

And I don't know what to use next... I want to have something like:

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'];}

Obviously the method is wrong because I get: "Invalid argument supplied for foreach()". Can anyone help me with getting the songs? Thanks in advance.

Was it helpful?

Solution

It should be this:

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

OTHER TIPS

mysql_fetch_array only loads one row, it should be like that

$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'];}

You have this tagged with codeigniter. If you've building a CodeIgniter application, you should probably use CI's database library:

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

Of course, the best practice is to have your user data and your favorites data in separate models, but this should work for now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top