$wpdb->get_results() returns good result only in first foreach iteration

I’ve got strange issue when I am using $wpdb->get_results() in content-single.php in Twenty Eleven theme. $wpdb->get_results() returns proper values only in first loop iteration. I’ve got simple function in functions.php called

function get_product_data($postid)
{
    global $wpdb;

    $meta_table = $wpdb->prefix.'postmeta';
    $product_table = $wpdb->prefix.'_features';

    $eans = get_post_meta($postid, '_bs_prod_sym');
    $eans = explode(';', $eans[0]);

    print_r($eans); // returns Array ( [0] => abcde [1] => abcd )
    foreach($eans as $ean)
    {
        $features = $wpdb->get_results("SELECT feature_name FROM $product_table WHERE product_id = '$ean'", ARRAY_A);  

        print_r($features);// returns Array ( [0] => Array ( [feature_name] =>  feature name 1 ) [1] => Array ( [feature_name] => feature name 2 ) [2] => Array ( [feature_name] => feature name 3 ) ) 

        foreach($features as $feature) 
        {  
            print_r($feature); // returns single element of $features array
        }
    }
}

And here is the place in content-single.php where I am calling get_product_data().

Read More
<div class="entry-content">
        <?php the_content(); ?>

        <?php get_product_data(get_the_ID()); ?>

        <?php wp_link_pages( array( 'before' => '<div class="page-link"><span>' . __( 'Pages:', 'twentyeleven' ) . '</span>', 'after' => '</div>' ) ); ?>
    </div><!-- .entry-content -->

Query in $features variable returns proper values only in first foreach iteration. If I change values in array $eans to Array ( [0] => abcd [1] => abcde ) (before it was Array ( [0] => abcde [1] => abcd )) I get proper values also only once. I am sure that queries are good and data in database are also ok.

Related posts

Leave a Reply