Problem getting meta_value data from array
-
Hi. I’m trying to put together a list of all posts where the metadata matches a specific query. It appears to work fine until I try to output the data, at which point it is repeated continuously.
I expected it to display 16 23 but instead it shows 16 23 16 23 16 23 16 23 16 23 16 23 16 23 16 23 16 23 16 23
Here’s the code:
<?php global $wpdb; $results =$wpdb->get_results("SELECT post_id FROM $wpdb->posts , $wpdb->postmeta where $wpdb->postmeta.meta_value = '2015/06/03' AND meta_key='mymvkey'", OBJECT); foreach ($results as $result){ print_r ($result->post_id); } ?>I’m still trying to get the hang of handling arrays (and not just in php) so that’s probably where I’m going wrong. But every post I’ve read suggests that this should work. Any way to stop it repeating and just display the data once?
-
Hi
Dunno whether you’ve solved this or not but just in case…
I’m no expert but I have learned how to debug (crudely or otherwise) my queries, etc.1 = The reason that you’re getting the duplicates is because of “, $wpdb->postmeta” which is, I think, returning all of your post_meta records.
2 = Your query needs to create a join between posts and post_meta. Something like this should work:
global $wpdb; $myquery = " SELECT ID FROM wp_posts INNER JOIN wp_postmeta ON wp_posts.ID = wp_postmeta.post_id WHERE wp_postmeta.meta_key='mymvkey' AND wp_postmeta.meta_value = '2015/06/03' ORDER BY wp_posts.ID ASC "; $myresults = $wpdb->get_results($myquery,OBJECT); foreach ($myresults as $myobject){ foreach($myobject as $mykey=>$myvalue) { echo "{$mykey}={$myvalue} "; } }3 = why not run the query on post_meta directly. Your query would look something like this:
$myquery = " SELECT post_id FROM wp_postmeta WHERE wp_postmeta.meta_key='mymvkey' AND wp_postmeta.meta_value = '2015/06/03' ORDER BY wp_postmeta.post_id ASC ";4 = If your output doesn’t make sense, then you need to see what your query has returned. I’d run print_r($myresults) on the line following the get_results command.
The topic ‘Problem getting meta_value data from array’ is closed to new replies.