It's not a great idea to store a multi-valued attribute in a single field. Ideally, you would have a Products table, a Tags table and a ProductTags Table.
However, you could select the Tags for the Product and use explode()
to get an array of Tags. The for each other product, do the same and use array_intersect
to get an array of common elements. Then use count() > 1
to determine if it's related
So:
function getRelatedProducts($productName)
{
$productResults = mysql_query("SELECT * FROM products WHERE productName = '$productName' LIMIT 0,1");
$relatedProducts = array();
if(mysql_num_rows($productResults) == 1)
{
$product = mysql_fetch_array($productResults);
$tags = explode(",",$product['tags']);
$otherProducts = mysql_query("SELECT * FROM products WHERE productName != '$productName'");
while($otherProduct = mysql_fetch_array($otherProducts))
{
$otherTags = explode(",",$otherProduct['tags']);
$overlap = array_intersect($tags,$otherTags);
if(count($overlap > 1)) $relatedProducts[] = $otherProduct;
}
}
return $relatedProducts;
}
It's a bit rough and ready but it should work. This code assumes you have columns called productName
and tags
.
PHP:array_intersect - Manual
If you go ahead with a product_tags table, you can use the following code to find related products:
function getRelatedProducts($productId)
{
$sql = "SELECT p.*,COUNT(*) AS matchedTags FROM products p
INNER JOIN product_tags pt ON pt.product_id = p.id
WHERE pt.tag_id IN (SELECT tag_id FROM product_tags WHERE product_id = $product_id)
GROUP BY p.id
HAVING COUNT(*) > 1";
$results = mysql_query($sql);
$relatedProducts = array();
while($result = mysql_fetch_array($results))
{
$relatedProducts[] = $result;
}
return $relatedProducts;
}
The important part is the SQL at the start of the function. It will give you the related products. Do with them what you will!