• Resolved kmeiding

    (@kmeiding)


    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?

Viewing 4 replies - 1 through 4 (of 4 total)
  • $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?

    Thread Starter kmeiding

    (@kmeiding)

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

    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' );
    Thread Starter kmeiding

    (@kmeiding)

    Thank you! That fixed it.

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Global $wpdb not working’ is closed to new replies.