Reputation: 513
I am working on a wordpress site with a custom theme, and I cannot figure out how to get $wpdb->prepare($query, $args) to work.
The Problem
I have a function in wp-content/themes/mytheme/php/functions.php which runs $wpdb->prepare($query, $args) to protect the query from SQL injection before executing the query and inserting some new data. However when I run this function, I get an error that reads "Call to a member function prepare() on null" on the line where $wpdb-prepare() is run. I did some googling and found that this means that $wpdb had not been defined.
What I tried
As per other threads I found online, I tried defining
global $wpdb
both inside my function and at the top of functions.php. When that didn't work I tried putting
include_one('/wp-includes/wp-db.php')
at the top of functions.php, but still nothing.
Does anyone have any other ideas about what I could try?
Upvotes: 0
Views: 222
Reputation: 804
It's calling to the function just fine, but it's finding no valid input (null). What are you using to define your table name? I've had it before where a $wpdb won't run unless I've predefined it like this:
global $wpdb;
$table = $wpdb->prefix . "table_name";
$sql = $wpdb->prepare( "SELECT * FROM {$table} ORDER BY something DESC");
$result = $wpdb->get_results( $sql , ARRAY_A );
Upvotes: 1