Web Hosting Talk







View Full Version : foreach used on a db


MGHosted.net
12-31-2004, 04:29 PM
Hi Guys,

I've tried to do something, and I know it wont work, but I can't seem to get my head around what I'm trying to do and write code for it.

This is my code


$exploded = explode(",", $currentfavourites);

foreach($exploded as $key=>$cid) {
if($cid == $id) {
echo "<br />Already in favourites";
} else {
echo "<br />Added to favourites!";
}
}


In some code above that, It queries a database, and then gets 1 row only, it then assigns one of the colums to $currentfavourites.

It's in this format: number,number,number (e.g. 1,2,3)

The one I'm using to test is 1,2

I'm on a page which is page.php?id= which also gets another query to get another row, which is different. The id for that row is $id.
So what my code does, is explode the 1,2 in 1 and 2, so I think loop it using the foreach, and then I say, if the ID is the same as the other ID, echo Already in favourites. So it'll go 1 = 1, and return already, then it'll go 1 = 2 and echo added when I dont want it to say that, I only want it for check the current ID.

If any of that makes sense, do you know a way to fix it?

error404
12-31-2004, 06:02 PM
Well first of all, you really should have a separate table for the favourites. It's bad practice to store more than one value in a single database column. You might want something as simple as a 3 value table holding the favourite_id, user_id (or some such link to your other table), and favourite_url or whatever you're storing. Then it's a simple matter of doing a single SELECT and JOIN (you don't even need the join if you're getting the id of the parent row directly...) to get the information you want. Something like SELECT favourite_id FROM favourites WHERE user_id=$id AND favourite_id=$_POST['id']. This will only return a row if that user has that particular favourite id.

Of course, I don't really know what you're doing, so more detail would be helpful...

MGHosted.net
01-01-2005, 04:52 PM
Hello,

I decided to just use the favourites table in the end, but at first, I did think I would save on room by doing it the other way. Everything works now.
Thanks for trying to help.

Burhan
01-02-2005, 03:08 AM
Instead of doing all that cruft, you could have just said :


if (in_array($id,explode(",",$currentfavourites)))
{
echo "Already in favorites";
} else {
echo "Not in favorites";
}