Jump to content

Archived

This topic is now archived and is closed to further replies.

tleisher

explode() and arrays

Recommended Posts

Alright, so here's how my database works. If someone adds a book as their favorite it takes their current favorite book column, adds "," and then the book name so it comes up  like "1,2,3".

Then in the favbook.php file, I want to have it display all the usernames of the people who have the book id in their fav_book column.

So far I figured that I should read that column with a mysql query, then mysql_fetch_array the query, and then explode(",", $fav_book);

But how would I do this in a loop so that it reads through the array and if it doesnt find $_GET["id"] then it doesn't print that username, then continues on to the next row with the new username and so on until it gets to the bottom of the table?

Share this post


Link to post
Share on other sites
[code]
foreach ($fav_book as $val) {
  if $(_GET['id'] == $val) {
      // print username or whatever
  }
}
[/code]

Share this post


Link to post
Share on other sites
Just a note.. this method of storage (delimeted list) is looked upon as 'sloppy' because, well, it is sloppy.

Use a table to store all the users entries with a foreign key for the user id and a foreign key for the book details. Essentiall 3 columns: index, userid, bookid.

Then select the rows from that table, with joins on users and books if necessary. It will be MUCH more efficient.

Share this post


Link to post
Share on other sites
So have a completely different table for favorites?

Like:

Userid - Book ID
1            2
1            5
3            2

and so on?

Share this post


Link to post
Share on other sites
yes, with it's own index field:

[code]CREATE TABLE `favorites`(
    `id` INT NOT NULL AUTO_INCREMENT,
    `bookid` INT NOT NULL,
    `userid` INT NOT NULL
) PRIMARY KEY(`id`);[/code]

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.