Link to home
Start Free TrialLog in
Avatar of Robert Granlund
Robert GranlundFlag for United States of America

asked on

PHP PDO foreach Statement

I have a PHP PDO Query that runs almost 100%, however, I have one issue I'm not sure how to fix:  
I am querying a Wordpress DB and have used JOIN to go through all of the appropriate tables to get the desired results:
The query:
	$user_id = get_current_user_id();


	$sql = "SELECT
    		p1.ID AS ID,
    		pm1.meta_value AS customer_id,
			oi1.order_item_id AS order_item_id,
			om1.meta_value AS first_name,
			om2.meta_value AS last_name,
			om3.meta_value AS mailing_address
			FROM wp_posts p1
			JOIN wp_postmeta pm1 ON (pm1.post_id = p1.ID AND pm1.meta_key = '_customer_user')
			JOIN wp_woocommerce_order_items oi1 ON (oi1.order_id = p1.ID)
			JOIN wp_woocommerce_order_itemmeta om1 ON (om1.order_item_id = oi1.order_item_id AND om1.meta_key = 'Applicant Information - First Name')
			JOIN wp_woocommerce_order_itemmeta om2 ON (om2.order_item_id = oi1.order_item_id AND om2.meta_key = 'Applicant Information - Last Name')
			JOIN wp_woocommerce_order_itemmeta om3 ON (om3.order_item_id = oi1.order_item_id AND om3.meta_key = 'Applicant Information - Mailing Address')
			WHERE p1.post_type = 'shop_order'";
	

	
	$customer = $pdo->prepare($sql);
 
	// EXECUTE QUERY
	try {
    	$customer->execute();
		$result = $customer->fetchAll();

foreach ($result as $row) {
	$cid = $row->customer_id;
	$fn = $row->first_name;
    	$ln = $row->last_name;
	if ($user_id == $cid) {
    		echo $fn.' '.$ln;
	}
}

Open in new window


The code grabs all of the Order details from the DB table wp_woocommerce_order_itemmeta.  Lets say there are three orders in the DB, each for a different product.  I'm going to grab each product name and list it out, however, I don't want to list my name three times, I want to echo it out only once.
Does that make sense?  What other info can I offer you to help me fix this issue?
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Try putting DISTINCT in the field list

SELECT DISTINCT ...
Avatar of Robert Granlund

ASKER

Can you elaborate?
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial