Reputation: 9855
I have a table in the following structure...
ID USER_ID INTEREST
1 290 soccer
2 290 tennis
3 290 badminton
4 560 netball
I want to grab all values from the table where the user id is equal to the session user id and assign them as variables.
I have the following which works but displays the data very peculiarly..
$interestsquery = "SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();
$result = mysql_query($interestsquery);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$interests[] = $row['interest'];
$interest1 = $interests[1];
$interest2 = $interests[2];
$interest3 = $interests[3];
print $interest1 . " - " . $interest2 . " - " . $interest3;
}
The above however outputs something along the lines of...
- - tennis - - tennis - badminton -
Can anybody see where I'm going wrong?
Upvotes: 0
Views: 1468
Reputation: 2193
$interests = array(); while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $interests[] = $row['interest']; } $int_count = count($interests); $i=0; foreach ($interests as $interest) { $var = 'interest' . ($i + 1); $$var = $interest; $i++; } print $interest1 . " - " . $interest2 . " - " . $interest3;
Upvotes: 0
Reputation: 14909
Think what happens to your loop at the first iteration:
in the second run:
and so on.
You need print the result when you exit the while loop (and the code is still flawed as it don't get the value into the index 0 of the array).
An alternative should be:
$interestsquery = "SELECT `interest` FROM `user_interests` WHERE `user_id` = "
. $usersClass->userID();
$result = mysql_query($interestsquery);
$interests = array();
// you fetch just a field, fetch_row will be sufficent
while($interest = mysql_fetch_row($result)) {
array_push($interests, $interest[0]);
}
echo implode(' - ', $interests);
Upvotes: 1
Reputation: 8334
This should do what you need:
$interestsquery = "SELECT `interest` FROM `user_interests` WHERE `user_id` = " . $usersClass->userID();
$result = mysql_query($interestsquery);
$interests = array();
while(list($interest) = mysql_fetch_array($result))
$interests[] = $interest;
print explode($interests, ' - ');
Upvotes: 2