0

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 $array2it 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?

1
  • use distinct at product name Commented Nov 4, 2015 at 9:50

4 Answers 4

1

use group by

group by Productname 

or you can try distinct

Sign up to request clarification or add additional context in comments.

2 Comments

may be duplicate data available in your table
if my answer helps you please accept my answer :) @MarcelW
1

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 

Comments

0

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 "); 

Comments

0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.