• Hi,
    Is there any reason a query constructed with wp database functions would return different results than one that is not.

    old method:

    	$query = "select count(distinct(t.title)) as num_of_items from title t 
    	WHERE t.description LIKE '%{$mysql["search"]}%' AND t.active = 1  "; 	 
    	$result = mysql_query( $query, $link );
    	$line = mysql_fetch_array( $result, MYSQL_ASSOC );
    	var_dump($line);

    new method:

    	$mysql["search"] = $wpdb->esc_like( $mysql["search"] );
    	$mysql["search"] = '%' . $mysql["search"] . '%';
    	$query = "select count(distinct(t.title)) as num_of_items from title as t 
    	WHERE t.description LIKE %s AND t.active = 1  "; 	 
    	$sql = $wpdb->prepare( $query, $mysql["search"]);
    	$num_of_items_arr = $wpdb->get_col($sql,0);
            var_dump($num_of_items_arr);

    As a side note:
    Why does the above query ($sql) echo out as:
    select count(distinct(t.title)) as num_of_items from title as t
    WHERE t.description LIKE ‘{84e1baeb63351ba70aa6c0513d7904e1bdf6ab1481cd18e2a75f8b8acd91dc2b}saga{84e1baeb63351ba70aa6c0513d7904e1bdf6ab1481cd18e2a75f8b8acd91dc2b}’ AND t.active = 1 “

    • This topic was modified 6 years, 5 months ago by Jan Dembowski.
    • This topic was modified 6 years, 5 months ago by bcworkz. Reason: code fixed
Viewing 1 replies (of 1 total)
  • Moderator bcworkz

    (@bcworkz)

    Short answer, no ??
    I tried your code on my site, adjusting table, fields, etc. to fit my data. Basically the same process, different specifics, so the results should be very similar. I did have to use mysqli in place of mysql, but that should make no difference.

    Both returned the same count value. One returned array was associative, the other indexed, but the values were the same.

    The hexadecimal search string in the $wpdb->prepare result is a memory address pointer to where your search data is stored. Code-wise, it’s no different than having the actual value in place.

    BTW, when you post code in these forums, please demarcate with backticks or use the code button. If you don’t do this, your code gets corrupted and it’s difficult for others to test your code. I fixed the code for you since I wanted to test it for myself. Regular members do not have such a luxury.

Viewing 1 replies (of 1 total)
  • The topic ‘query with $wpdb->prepare has different results’ is closed to new replies.