Reputation: 2679
I got a sql table containing a string that i need to join in another table. First i got the string from the SQL table:
$sql = "Select coupons.restrict_to_products From coupons Where coupons.coupon_id = 2";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$array2=implode(",", $row);
So if I now echo $array2
it shows me "42, 43, 73" which is what i needed. Now i am trying to join another table with the result like this:
$query = mysql_query("SELECT products_name FROM products_description WHERE products_id IN ($array2)");
while ($row2 = mysql_fetch_assoc($query)) {
$array3=implode(",", $row2);
echo $array3."<br>";
}
The code works but for some reason it shows me every productname 3 times and not only once. The result of the echo
is:
Productname 1
Productname 1
Productname 1
Productname 2
Productname 2
Productname 2
Productname 3
Productname 3
Productname 3
What am I missing?
Upvotes: 0
Views: 93
Reputation:
Or if the rows aren't duplicate, you can grab all the names associated with those ids
SELECT products_id,GROUP_CONCAT(products_name) AS products_names FROM products_description WHERE products_id IN ($array) GROUP BY products_id
Upvotes: 0
Reputation: 2522
Use this
$query = mysql_query("SELECT DISTINCT(products_name) FROM products_description WHERE products_id IN ($array2) ");
while ($row2 = mysql_fetch_assoc($query)) {
$array3=implode(",", $row2);
echo $array3."<br>";
}
OR
$query = mysql_query("SELECT products_name FROM products_description WHERE products_id IN ($array2) group by products_id ");
Upvotes: 0
Reputation: 31749
The coupons might have applied to same products so it is returning 3
times the same product. Try to group
the products by id
which would be unique. Try -
SELECT products_name
FROM products_description
WHERE products_id IN ($array2)
GROUP BY products_id
Upvotes: 1