I have a plugin folder foobar.
Inside this plugin I have a page called foobar.php. Inside this page I have
global $wpdb;
$orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'name'; //If no sort, default to title
$sql = "SELECT * FROM wp_nc_location ORDER BY " . $orderby;
$data = $wpdb->get_results($sql);
This query works inside of my foobar.php page. However, in the same folder I have another page called process.php, and when I include the identical code:
global $wpdb;
$orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'name'; //If no sort, default to title
$sql = "SELECT * FROM wp_nc_location ORDER BY " . $orderby;
$data = $wpdb->get_results($sql);
I get the error message:
Fatal error: Call to a member function get_results() on a non-object in...
Why doesn’t the global $wpdb appear to work in the other page? (process.php)?
The
$wpdb
object is part of WordPress, so wouldn’t be loaded into a standalone PHP page as it is into a WordPress template.You might want to look into creating your own page templates, then you could run your database query as part of that page template.
As a side note: You are currently trusting input from the user (
$_REQUEST
) which is a Bad Thingâ¢, as it could make you vulnerable to SQL Injection attacks. The code example you give could be adapted as below to be less vulnerable:I’ve not tested the above code, but the key thing is to check the value of
$orderby
is known to be safe before you put it into the DB query.