I cannot properly call $wpdb - wordpress

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?

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 );

Related

Custom function error to produce a shortcode resulted in white screen of death

I followed the syntax the best I could to create a shortcode on execution, I got the wsod. Once removed, all was well. But I don't know what is wrong with my code. This code sits inside 'My Custom Functions', a plugin for wp.
In researching how to write a custom shortcode, I discovered instructions here: https://torquemag.io/2017/06/custom-shortcode/ My expertise is in mysql and use mostly plugins in our wordpress website. I am very limited with coding.
function last_updated_shortcode {
$last_updated = $wpdb->get_results( "SELECT MAX(process_time) FROM
qgotv.last_updated");
return $last_updated;
}
add_shortcode( 'last_updated', 'last_updated_shortcode' );
This shortcode should retrieve a max(datetime value) from a db table so it can be displayed on a page. The query works. The qgotv db is separate from the wordpress db but can be accessed through wp.
Two issues I can see, one is that you have a syntax error in your function. When defining a function in PHP, you need to include the arguments parenthesis: function my_function(){ /* Do Stuff */ }. Also, you probably need to reference the $wpdb with the global keyword.
You can read up a bit on the $wpdb class as well as creating your own functions.
This should get you sorted out:
add_shortcode( 'last_updated', 'last_updated_shortcode' );
function last_updated_shortcode(){
global $wpdb;
$last_updated = $wpdb->get_results( "SELECT MAX(process_time) FROM qgotv.last_updated");
return $last_updated;
}

How to access Wordpress' global $wpdb from PHP?

I'm trying to execute a query in PHP against a MySQL database. My code is below:
<?php
require_once ("wp-includes/wp-db.php");
global $wpdb;
$myrows = $wpdb->get_results( "SELECT id, name FROM wp_db_posts" );
echo $myrows;
?>
After executing this code, I get a Fatal error: Call to a member function get_results() on null in C:\Apache24\htdocs\wordpress\me.php on line 4
I'm actually new to WordPress and want to know exactly how can I access the $wpdb global variable from PHP. My databses are pre-fixed with wp_db_.
What am I doing wrong? Can anyone help me here?
assuming you script placed in the root directory of WordPress you should load wordpress not access the wp-db.php directly so your code should be like this:
<?php
require_once "wp-load.php";
global $wpdb;
$myrows = $wpdb->get_results( "SELECT ID, post_name FROM {$wpdb->prefix}posts" );
and you can't echo myrows as you will get object not string you should use instead
var_dump() or print_r()

Accessing plugin database table in functions.php

I'm trying to access a plugin's database from functions.php. With the code below, there are no errors, but there is no data echoing either. By looking around the web there are so many answers for so many different circumstances and none helped me apply any fixes to this particular code.
function show_review_count() {
global $wpdb;
$dbtable = 'wpcreviews';
$pageID = 4745;
$row = $wpdb->get_results("SELECT COUNT(*) AS `total` FROM `$dbtable` WHERE `page_id`=$pageID AND `status`=1");
echo $row[0]->total;
}
You're missing $wpdb's table prefix:
$dbtable = $wpdb->prefix . 'wpcreviews';

When is $wp_query initialized and how to override it?

I am trying to write a new query function using WP_Query object.
I created a new template file and put the followings:
$query_args = array(
'post_type' => 'page',
'post_parent=41',
);
// The Featured Posts query.
$results = new WP_Query($query_args);
But whatever arguments I use, the query does not change. It looks as if the query is already initialized and creating a new WP_Query does not have any effect on the existing query.
The only wordpress function called before my code is get_header() which does not include any call to WP_Query or query_posts.
I put the following line to find out what the actual sql query is:
echo $GLOBALS['wp_query']->request;
The actual sql query is:
SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND (wp_posts.ID = '14') AND wp_posts.post_type = 'page' ORDER BY wp_posts.post_date DESC
This query does not change when I change my $query_args.
I wonder when the global variable $wp_query is initialized and what should I do to use my own query?
You are creating a new WP_Query object and saving it to $results. That is where the results of your query will be, not in $GLOBALS['wp_query']. Of course it doesn't overwrite $wp_query. They are different things. Try var_dump($results) instead.
You can overwrite $wp_query by creating a new WP_Query object like so: $wp_query = new WP_Query($query_args);. But that isn't efficient. You run two queries when you only need one. The better way to do it is to hook into pre_get_posts. Something like:
function alter_query_so_15250127($qry) {
if ( $qry->is_main_query() && is_page('featured-posts-page') ) {
$qry->set('post_type','page');
$qry->set('post_parent',41);
}
}
add_action('pre_get_posts','alter_query_so_15250127');
The if conditional is very important. You need to use that line to make sure the filter fires only on the page(s) you want it to fire on. Your question does not have enough detail for me to work out the precise conditions.
Have a look at the following diagram as posted in http://codex.wordpress.org/Function_Reference/query_posts

Using $wpdb object in Wordpress functions.php file

I have an issue with not being able to call the get_results() function on the $wpdb object inside the Wordpress functions.php file.
Exact error: Call to a member function get_results() on a non-object in [...]
This is my function;
global $wpdb;
function query_students($year){
$wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM {$wpdb->prefix}usermeta WHERE meta_key ='foobar' AND meta_value = '{$year}'"
)
);
$wpdb->flush();
}
As you can see I've globalised the $wpdb variable, and this function works great in the page template file. I would just prefer it if my functions weren't dotted around the place, and in some kind of centralised file.
Thanks in anticipation! :)
"Globalizing" a variable that's already in global scope does nothing. Case and point:
global $a; //does nothing
$a = 'foo';
global $a; //does nothing
foo();
echo $a; //'foo'
bar();
echo $a; //'bar'
function foo()
{
$a = 'bar';
}
function bar()
{
global $a;
$a = 'bar';
}
The global keyword does not permanently make the defined variable global in scope. Think of it as a way to define a variable in a function and set its value to whatever a variable with the same name is outside of the function.
You need to move your global declaration INTO the function to make the $wpdb object in the Global scope available within the function's scope:
function query_students($year){
global $wpdb;
$wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM {$wpdb->prefix}usermeta WHERE meta_key ='foobar' AND meta_value = '{$year}'"
));
$wpdb->flush();
}
I was running following query in functions.php
SELECT `id`, `user`, `width`, `type`, `source`, `link`, `expire`, `impressions`, `clicks` FROM adds WHERE `width`=728 and `impressions` < (SELECT max(`impressions`) FROM adds WHERE `width`=728 ) or `width`=728 and `clicks` < (SELECT max(`clicks`) FROM adds WHERE `width`=728 ) ORDER BY RAND() LIMIT 3
it was not working but after adding the line
global $wpdb in the begining of the function helped me and query is running fine.
Thanks

Resources