view raw
Vivek Padhye Vivek Padhye - 1 year ago 36
SQL Question

How to return a MySQL string from within a PHP function?

I want to reuse the same MySQL query, so thought wrapping it in PHP function might help. I did it as follows:

function fetch_from_db($criteria) {
global $wpdb;
$qvar = $wpdb->get_results("select * from $wpdb->terms, $wpdb->term_taxonomy where $wpdb->terms.term_id = $wpdb->term_taxonomy.term_taxonomy_id and $wpdb->term_taxonomy.taxonomy = %s", $criteria);
return $qvar;
$get_two_wheeler_make = fetch_from_db('2-wheeler-make');

but things are not working and it is returning
. How do I make it work? What is wrong in the code?


First, this is a great resource Class Reference $wpdb. The , is making you $criteria the object type being return, not the search criteria; therefore, %s is empty. Add $criteria to the query string. And try again.

$qvar = $wpdb->get_results("SELECT * FROM $wpdb->terms, $wpdb->term_taxonomy
   WHERE $wpdb->terms.term_id = $wpdb->term_taxonomy.term_taxonomy_id
   AND $wpdb->term_taxonomy.taxonomy = '".$criteria."'");