WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Problem with $wpdb->get_var (2 posts)

  1. Phizz
    Member
    Posted 1 year ago #

    Can anyone shed some light on why the following doesn't work:

    function cat_has_products($id) {
    	global $wpdb;
    
    	$sql = "SELECT term_taxonomy_id from wp_term_taxonomy where term_id = $id;";
    	$termtaxid = $wpdb->get_var ($wpdb->prepare( $sql) );
    	echo "ID = $id <br>";
    	echo "Term id = $termtaxid <br>" ;
    	$catprodcount = $wpdb->get_var ($wpdb->prepare( "select count(object_id) from $wpdb->term_relationships where term_taxonomy_id = $termtaxid;") );
    	echo "Count is : <br>" . $catprodcount;
    	//return $catprodcount;
    
    }

    Typical output is as follows:

    ID = 96
    Term id =
    Count is :

    where 96 is the value passed to the function. The problem seems to be with the line:
    $termtaxid = $wpdb->get_var ($wpdb->prepare( $sql) );
    - $termtaxid is not receiving a result. However, if I hardcode the value for $id into the $sql query, $termtaxid receives the correct value.

    Similarly, if I hardcode the value for $termtaxid into the last query $catprodcount = $wpdb->get_var ($wpdb->prepare( "select count(object_id) from $wpdb->term_relationships where term_taxonomy_id = $termtaxid;") );, $catprodcount receives a value.

    I hope someone can help - I am tearing my (rapidly diminishing) hair out here.

  2. Phizz
    Member
    Posted 1 year ago #

    I solved this myself. The problem was in the value I was passing into the routine, which I had calculated using a do_shortcode() function. Examining the error logs for the MYSQL server, I realised that rather than passing the value it was passing the shortcode itself.

    My bad.

Topic Closed

This topic has been closed to new replies.

About this Topic