Using $wpdb object in Wordpress functions.php file - wordpress

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

Related

Get parameter from url and pass it in add_filter not returning dynamic value wordpress

I am facing a weird problem. I am trying to override value in a function using apply_filter.
Here is the code which I am using in the theme's functions.php file:
function customized_params_6e9668( $attrs ) {
$subfolder = isset($_GET["sub"]) ? '/'.$_GET["sub"] : '';
$attrs["folder"] = $attrs["folder"].$subfolder; // if getting the value from the url then not working in this case
//$attrs["folder"] = $attrs["folder"]."/testing"; // if I use static name then working in this case
echo $attrs["folder"];
return $attrs;
}
add_filter( "customized_params_6e9668", "customized_params_6e9668");
Here is the function where I am using apply_filter to override the values in the plugin's file.
function getFolderData(){
global $wpdb;
$folder_data = $wpdb->get_row(
$wpdb->prepare(
'SELECT * FROM ' . $wpdb->prefix . 'folders WHERE key=%s',
trim(sanitize_text_field($_REQUEST["data_key"]))
)
);
if(!empty($folder_data)){
$folder_data = apply_filters( 'customized_params_'.$folder_data->key, $folder_data );
print_r($folder_data);
}
}
This function is getting the list of data from the database. overriding the value of the folder using add_filter.
Please correct me where I am doing wrong.
Thanks in advance.

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

I cannot properly call $wpdb

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

Wordpress custom plugin shortcode wpdb unknown

I'm writing a custom plugin in wordpress and I'm using a shortcode for the first time.
Until now my shortcode works but now I want to execute a query in the function of that shortcode to get all the employees from a specific employee group id
[employee_group_tag group_id=2]
This is the file that has my shortcode functionality:
<?php
/*
Plugin Name: Employees
Plugin URI: xxx
Description: xxx
Version: 1.0
Author: xxx
Author URI: http://www.blabla.com
*/
global $wpdb;
function employee_shortcode_func( $atts ) {
extract( shortcode_atts( array(
'group_id' => '0',
), $atts ) );
// Alle werknemers ophalen adhv van group_id
$sql = 'SELECT * FROM wp_werknemers_employees WHERE employee_employee_group_id = ' . $group_id;
$results = $wpdb->get_results($sql);
return 'test';
}
add_shortcode( 'employee_group_tag', 'employee_shortcode_func' );
But when I run this it gets stuck on $wpdb->get_results($sql) because when I leave this out it displays my page correctly but when I want to fill it with employee details I only get the half of my page. So it "breaks"
I tried to do (which works in all my other files)
require_once("../../../wp-config.php")
But it doesn't work...
Is it possible that it's not working because its in my "main" plugin file? Because in all my other files I can use wpdb when I use the require function...
any ideas?
From the PHP Manual:
For the most part all PHP variables only have a single scope. This single scope spans included and required files as well. For example:
$a = 1;
include 'b.inc';
Here the $a variable will be available within the included b.inc script. However, within user-defined functions a local function scope is introduced. Any variable used inside a function is by default limited to the local function scope. For example:
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
The last example does not work, as $a is not defined inside the scope of the function.
Just like in your case, for it to work you have to use:
function employee_shortcode_func( $atts ) {
global $wpdb;
// etc
}

setting variable in header.php but not seen in footer.php

in wordpress ,
i set a variable in header.php
<?php
$var= 'anything'
?>
but in footer.php when I echo it
<?php
echo $var;
?>
I got no thing printed ... why !>
You're not in the same scope, as the header and footer files are included in a function's body. So you are declaring a local variable, and referring to another local variable (from another function).
So just declare your variable as global:
$GLOBALS[ 'var' ] = '...';
Then:
echo $GLOBALS[ 'var' ];
I know you've already accepted the answer to this question; however, I think there's a much better approach to the variable scope problem than passing vars into the $GLOBALS array.
Take the functions.php file in your theme for example. This file is included outside the scope of the get_header() and get_footer() functions. In fact it supersedes anything else you might be doing in your theme (and I believe in the plugin scope as well--though I'd have to check that.)
If you want to set a variable that you'd like to use in your header/footer files, you should do it in your functions.php file rather than polluting $GLOBALS array. If you have more variables that you want to sure, consider using a basic Registry object with getters/setters. This way your variables will be better encapsulated in a scope you can control.
Registry
Here's a sample Registry class to get you started if:
<?php
/**
* Registry
*
* #author Made By Me
* #version v0.0.1
*/
class Registry
{
# +------------------------------------------------------------------------+
# MEMBERS
# +------------------------------------------------------------------------+
private $properties = array();
# +------------------------------------------------------------------------+
# ACCESSORS
# +------------------------------------------------------------------------+
/**
* #set mixed Objects
* #param string $index A unique index
* #param mixed $value Objects to be stored in the registry
* #return void
*/
public function __set($index, $value)
{
$this->properties[ $index ] = $value;
}
/**
* #get mixed Objects stored in the registry
* #param string $index A unique ID for the object
* #return object Returns a object used by the core application.
*/
public function __get($index)
{
return $this->properties[ $index ];
}
# +------------------------------------------------------------------------+
# CONSTRUCTOR
# +------------------------------------------------------------------------+
public function __construct()
{
}
}
Save this class in your theme somewhere, e.g. /classes/registry.class.php Include the file at the top of your functions.php file: include( get_template_directory() . '/classes/registry.class.php');
Example Usage
Storing variables:
$registry = new Registry();
$registry->my_variable_name = "hello world";
Retrieving variables:
echo '<h1>' . $registry->my_variable_name . '</h1>'
The registry will accept any variable type.
Note: I normally use SplObjectStorage as the internal datastore, but I've swapped it out for a regular ole array for this case.
I know this is a bit old question and with a solution voted but I though I should share another option and just found a better solution (that works) without using Globals
function fn_your_var_storage( $var = NULL )
{
static $internal;
if ( NULL !== $var )
{
$internal = $var;
}
return $internal;
}
// store the value
fn_your_var_storage( 'my_value' );
// retrieve value
echo fn_your_var_storage(); // print my_value
try this code
first define your initial variable
$var="something";
then use the $_GLOBALS
$_GLOBALS['myvar']=$var;
and finally use the global variable in anywhere you want
global $myvar;
define string inside the $_GLOBALS as taken as global variable name or use the $_GLOBALS['myvar'] direct into the code without using the global
In wordpress Header, any template, Footer is different functions so you have to declare any varible as a global variable then you can access it .
/** header.php **/
<?php
global $xyz;
$xyz="123456"; ?>
/** Template.php or Footer.php **/
<?php
echo $xyz; ///return 123456
?>

Resources