Jump to content

Returning limited results in foreach


Go to solution Solved by dalecosp,

Recommended Posts

function getSimilarProducts() {
global $wpdb;

$out ="";

$Simprod = "SELECT DISTINCT (pr.prod_id), pr.prod_image
FROM products as pr
LEFT JOIN category_assoc as assoc 
ON assoc.prod_id = pr.prod_id
WHERE pr.companyB = '1' 
AND assoc.cat_id = '28' 
AND pr.prod_active = '1' LIMIT 3";
	

$SIM = $wpdb->get_results($Simprod, ARRAY_A);
 

	echo "These are similar products you may like.";

	
		foreach($SIM as $sample) {

		$out .= "<img src='". $this->imgLink . "/".$sample['prod_image']. "' />";

	
	echo $out;

	}

	
}

I have a simple query I tested in phpmyAdmin. Returns the limit results I need. But when I run my function I get duplicates, it returns 6 results all the same ID.

Link to comment
https://forums.phpfreaks.com/topic/303283-returning-limited-results-in-foreach/
Share on other sites

  • Solution

You're echoing "$out" inside the foreach loop ... and you're also concatenating to it with ".=" ... I think you probably want to put the echo statement AFTER the foreach loop?

 

(That is, after the first bracket and before the bracket that closes your function.)

Edited by dalecosp
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.