Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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().

<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.

share|improve this question
    
print_r($feature) returns Array ( [feature_name] => feature name 1 ) and then stops? Nothing else? If $features look like your code comment says it does, that makes no sense. –  s_ha_dum Oct 16 '12 at 14:59
    
Check that items in $eans after explode() don't have lingering whitespace in them. –  Rarst Oct 16 '12 at 18:29
    
I'm assuming $features is what it should return, as if it did return that, your code would work. Try var_dump($ean) in your first loop and make sure that the length is good (i.e. no whitespace, as @Rarst mentioned). If you have whitespace, replace $ean with trim($ean) in the foreach() statement. –  David Gard Jul 31 '13 at 14:06
    
As an aside, your function seems to be doing nothing other than querying, yet you are running lots of individual queries. Far more efficient to run on query and order the results. –  David Gard Jul 31 '13 at 14:07
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.