$wpdb doesn’t appear to work on page inside of a plugin

I have a plugin folder foobar.

Inside this plugin I have a page called foobar.php. Inside this page I have

Read More
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)?

Related posts

Leave a Reply

1 comment

  1. 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:

    global $wpdb;
    $orderby = $_REQUEST['orderby'];
    // Limit the values of orderby to ones we know to be safe
    $acceptable_orderbys = array( 'name', 'age', 'height' );
    if ( in_array( $orderby, $acceptable_orderbys ) )
        $clean_orderby = $orderby;
    else
        $clean_orderby = 'name';
    $sql = "SELECT * FROM wp_nc_location ORDER BY $clean_orderby";
    $data = $wpdb->get_results($sql); 
    

    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.