0

I'm trying to remove duplicates from the result of a foreach loop:

foreach ($tags as $tag) {
    $sql = "SELECT url,title,image,gift FROM listings LEFT JOIN tags ON listings.id=tags.product_id INNER JOIN tag_names ON tags.tag_id=tag_names.tag_id WHERE tag_names.tag_name=? and id!=$id ORDER BY RAND() LIMIT 5";
    $stmt = mysqli_prepare($mysqli, $sql);
    $stmt->bind_param('s',$tag[0]);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_all();

    if (count($row) > 0) { 
        echo etc. 
    }

The problem is I don't know how to skip echoing duplicate products under the different tags. I.e.

The same product can be under the tag A and under the tag B, but I only want it to be displayed once.

Any help would be appreciated.

Naveed Ramzan
  • 3,565
  • 3
  • 25
  • 30
Gremlin
  • 39
  • 7

2 Answers2

0

First fetch a whole data set using for example clause 'IN' and then iterate. You will have only one query.

The problem with this is that each query has quite a bit of overhead. It is much faster to issue 1 query which returns 100 results than to issue 100 queries which each return 1 result. This is particularly true if your database is on a different machine which is, say, 1-2ms away on the network. In this case, issuing 100 queries serially has a minimum cost of 100-200ms, even if they can be satisfied instantly by MySQL.

https://secure.phabricator.com/book/phabcontrib/article/n_plus_one/

John Smith
  • 1,091
  • 9
  • 17
-1
foreach ($tags as $tag) {
    $sql = "SELECT distinct url,title,image,gift FROM listings LEFT JOIN tags ON listings.id=tags.product_id INNER JOIN tag_names ON tags.tag_id=tag_names.tag_id WHERE tag_names.tag_name=? and id!=$id ORDER BY RAND() LIMIT 5";
    $stmt = mysqli_prepare($mysqli, $sql);
    $stmt->bind_param('s',$tag[0]);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_all();

    if (count($row) > 0) { 
        echo etc. 
    }
}

Try this.

Naveed Ramzan
  • 3,565
  • 3
  • 25
  • 30
  • Already tried with no success since the same products under different tags are being returned in different arrays. – Gremlin Jan 25 '17 at 06:56