Forums

[resolved] Global $wpdb not working (5 posts)

  1. kmeiding
    Member
    Posted 7 months ago #

    I am writing a plugin for a website I'm working on and am having trouble accessing the database. This code is supposed to retrieve a comment from a table I created with the name wp_motivational_comments. I just did the table by hand because I was having trouble and this plugin is so specific it most likely will never be used on any site.

    Here's the code to select from the database.

    global $wpdb;
    
    	$sql = "SELECT comment FROM " . $wpdb->prefix . "motivational_comments WHERE id = " . $_SESSION['comments'][$month - 1];
    	echo $sql;
    	$this_months_comment = $wpdb->get_var($sql);

    I get this error when I get to this page;

    Fatal error: Call to a member function get_var() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-content/plugins/EMSMSimulator/results.php on line 55

    When I printed out the sql statement, it was:

    SELECT comment FROM motivational_comments WHERE id = 19

    This is the first time I have worked with PHP or WordPress plugins and I've tried to do some research and can't find a solution to my problem.

    If I am understanding things correctly, the $wpdb->prefix should put the wp_ prefix on the table name but it is not working the way I think it should.

    Can anyone help?

  2. Big Bagel
    Member
    Posted 7 months ago #

    $wpdb is empty for whatever reason; you can check with var_dump( $wpdb );.

    Is results.php being included from your main plugin file (if it's not the main file), or are you accessing it directly?

  3. kmeiding
    Member
    Posted 7 months ago #

    results.php is the form action from the previous page.

  4. Big Bagel
    Member
    Posted 7 months ago #

    WordPress doesn't get loaded when results.php is accessed directly. Thus, a nonexistent $wpdb. To load up WordPress so you can use its global variables and functions, try including/requiring wp-load.php beforehand. Something like:

    require( '/path/to/wp-load.php' );
  5. kmeiding
    Member
    Posted 7 months ago #

    Thank you! That fixed it.

Reply

You must log in to post.

About this Topic

Tags